Showing posts with label select. Show all posts
Showing posts with label select. Show all posts

Friday, March 30, 2012

How to create SELECT?

I have the two following tables:

tblProject:
ProjectID
5001
5002
6001
6002
7001
7002

tblProject_type:
ProjectTypeID ProjectIDFrom ProjectIDTo
A 5000 5999
A 7000 7999

I need to create a SELECT statement which shows all records from
tblProjects WHERE ProjectTypeID = A. In this case every project except
6001 and 6002.

Unfortunately I can't have the ProjectTypeID in tblProject because each
project can belong to many project types. I know it sounds crazy but
that's the way my customers company is organized.

I'm very grateful for help in the right direction!

Regards,

SCREATE TABLE tblProjects(ProjectID INT)
INSERT INTO tblProjects(ProjectID) VALUES(5001)
INSERT INTO tblProjects(ProjectID) VALUES(5002)
INSERT INTO tblProjects(ProjectID) VALUES(6001)
INSERT INTO tblProjects(ProjectID) VALUES(6002)
INSERT INTO tblProjects(ProjectID) VALUES(7001)
INSERT INTO tblProjects(ProjectID) VALUES(7002)

CREATE TABLE tblProject_type(ProjectTypeID CHAR(1),ProjectIDFrom
INT,ProjectIDTo INT)
INSERT INTO tblProject_type(ProjectTypeID,ProjectIDFrom,Projec tIDTo)
VALUES('A',5000,5999)
INSERT INTO tblProject_type(ProjectTypeID,ProjectIDFrom,Projec tIDTo)
VALUES('A',7000,7999)

SELECT ProjectID
FROM tblProjects
WHERE EXISTS (SELECT * FROM tblProject_type
WHERE ProjectID BETWEEN ProjectIDFrom AND ProjectIDTo
AND ProjectTypeID='A')|||sta...@.gmail.com wrote:
> I have the two following tables:
> tblProject:
> ProjectID
> 5001
> 5002
> 6001
> 6002
> 7001
> 7002
> tblProject_type:
> ProjectTypeID ProjectIDFrom ProjectIDTo
> A 5000 5999
> A 7000 7999
> I need to create a SELECT statement which shows all records from
> tblProjects WHERE ProjectTypeID = A. In this case every project except
> 6001 and 6002.

Try:

SELECT projectid
FROM tblProject AS P
WHERE NOT EXISTS
(SELECT *
FROM tblProject_type AS T
WHERE P.projectid BETWEEN T.projectidfrom AND T.projectidto
AND T.projecttypeid = 'A');

> Unfortunately I can't have the ProjectTypeID in tblProject because each
> project can belong to many project types. I know it sounds crazy but
> that's the way my customers company is organized.

Instead of what you posted, a more common solution would be:

CREATE TABLE tblProject_ProjectType
(projectid INTEGER NOT NULL
REFERENCES tblProject (projectid),
projecttypeid CHAR(1) NOT NULL
REFERENCES tblProjectType (projecttypeid),
PRIMARY KEY (projectid, projecttyypeid);

There isn't necessarily anything wrong with what you posted and your
version certainly could make for a smaller table but it's also hard to
avoid redundancy. Specifically, you would have to use a trigger to
prevent overlapping ranges of rows for the same type - otherwise you
could get duplicate rows out of joins, which could give you incorrect
results.

The benefit of my tblProject_ProjectType version is that there is no
redundancy and joins to the table are always equijoins.

Hope this helps.

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/...US,SQL.90).aspx
--|||Thank's a lot for excellent help!

Regards,

S|||Thank's a lot for excellent help!

Regards,

S

How to create SELECT QUERRY FOR "A CHANGE ORDER FORM" in ASP?

Hello.
Hope you are all well and having a good day.
I've got a problem i would like you to help me out with. My
company has got a client who sells meat and my senior tech lead
has customized the cart to fit their needs and have created a
despatch table with a "simple asp form" that allows them
to scan their products in with a wi-fi scanner.

The despatch table has the following fields:
1. OrderID
2. Product
3. Quantit
4. sellbydate
5. traceabilitycode and
6. Weight
Question 1: how do i create a form in asp that allow a user to
view the order no, product and quantity
celibate,traceabilitybycode and Weight after scanning the
details into the simple form created?
Question 2: How can i create an asp form that allows users to
search for the Order that populates the orderid, Product,
quantity?
Question 3: How can i create an asp for that allows users to
search for Product with orderid,traceabilitycode and quantity?
Question 4: How can i create an asp form that allows users to
Trace: Orderid, traceabilitycode, sellbydate and Quantity?

Please find below the source code of both the:
despatchLotsRowsSimpleForm.asp that allow them to scan details
into the table and the despatchLotsExec.asp:

THE FORM:
<!#include file="../includes/settings.asp">
<!#include file="../includes/getSettingKey.asp">
<!#include file="../includes/sessionFunctions.asp">
<!#include file="../includes/databaseFunctions.asp">
<!#include file="../includes/screenMessages.asp">
<!#include file="../includes/currencyFormat.asp"
<%
on error resume next

dim mySQL, connTemp, rsTemp

' get settings
pStoreFrontDemoMode =
getSettingKey("pStoreFrontDemoMode")
pCurrencySign = getSettingKey("pCurrencySign")
pDecimalSign = getSettingKey("pDecimalSign")
pCompany = getSettingKey("pCompany")

pAuctions = getSettingKey("pAuctions")
pAllowNewCustomer = getSettingKey("pAllowNewCustomer")
pNewsLetter = getSettingKey("pNewsLetter")
pStoreNews = getSettingKey("pStoreNews")
pSuppliersList = getSettingKey("pSuppliersList")
pRssFeedServer = getSettingKey("pRssFeedServer")

%>
<b><%=getMsg(10021,"despatch")%></b>
<br>
<%=getMsg(10024,"Enter despatch ...")%
The despatchExec.asp Page
<%
' WebShop 3.0x Shopping Cart
' Developed using ASP
' August-2002
' Email(E-Mail address blocked: See forum rules) for further information
' (URL address blocked: See forum rules)
' Details: add e-mail to newsletter list
%
<!--#include file="../includes/settings.asp"-->
<!--#include file="../includes/getSettingKey.asp"-->
<!--#include file="../includes/databaseFunctions.asp"-->
<!--#include file="../includes/stringFunctions.asp"-->
<!--#include file="../includes/miscFunctions.asp"-->
<!--#include file="../includes/screenMessages.asp"-->
<!--#include file="../includes/sendMail.asp"--
<%

on error resume next

dim mySQL, connTemp, rsTemp, pEmail

' get settings

pStoreFrontDemoMode = getSettingKey("pStoreFrontDemoMode")
pCurrencySign = getSettingKey("pCurrencySign")
pDecimalSign = getSettingKey("pDecimalSign")
pCompany = getSettingKey("pCompany")

pEmailSender= getSettingKey("pEmailSender")
pEmailAdmin= getSettingKey("pEmailAdmin")
pSmtpServer= getSettingKey("pSmtpServer")
pEmailComponent= getSettingKey("pEmailComponent")
pDebugEmail= getSettingKey("pDebugEmail")
pGiftRandom= getSettingKey("pGiftRandom")
pPercentageToDiscount= getSettingKey("pPercentageToDiscount")
pStoreLocation = getSettingKey("pStoreLocation")

' form
pidOrder = lcase(getUserInput(request.form("idOrder"),50))
pProduct = lcase(getUserInput(request.form("product"),50))
pQuantity = lcase(getUserInput(request.form("quantity"),50))

pPriceToDiscount = 0

' insert despatch

mySQL="INSERT INTO despatch2 (idOrder, product, quantity ) VALUES ('"&pidOrder& "', '" &pProduct& "', '" &pQuantity&"')"

call updateDatabase(mySQL, rstemp, "despatchExec")

pBody=getMsg(10025,"Despatch confirmed...") &VBcrlf&getMsg(311,"To opt-out click at:") & " (URL address blocked: Seeforum rules)="&pEmail

response.redirect "redit_message.asp?message="&Server.Urlencode(getMsg(10025,"Despatch confirmed"))

call closeDb()
%
Thank you for your help in advance..
Regards,
philip

That's ASP, not ASP.NET, and you definately aren't using the SqlDataSource control. You may have better luck asking your question in a different forum.

|||

Thanks Motley...

sql

How to create reports dinamically?

Hello. Can I make a report for example with all the columns and make a
program in asp.net in which the user can select the columns he wants to see?
Thanks.Yes of course, unless RDL is a open Language you can stick your parts
together as the User wants. But I would keep in mind that there are already
thrid party tools to do that, therefore looking at these will eventually
save you time and money fordeveloping that on your own.
--
HTH, Jens Suessmeyer.
--
http://www.sqlserver2005.de
--
"Luis Esteban Valencia" <levalencia@.avansoft.com> schrieb im Newsbeitrag
news:OZDxaTydFHA.1684@.TK2MSFTNGP09.phx.gbl...
> Hello. Can I make a report for example with all the columns and make a
> program in asp.net in which the user can select the columns he wants to
> see?
> Thanks.
>|||Your page doesnt work
"Jens Süßmeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> escribió
en el mensaje news:elyDct0dFHA.220@.TK2MSFTNGP12.phx.gbl...
> Yes of course, unless RDL is a open Language you can stick your parts
> together as the User wants. But I would keep in mind that there are
already
> thrid party tools to do that, therefore looking at these will eventually
> save you time and money fordeveloping that on your own.
> --
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
> "Luis Esteban Valencia" <levalencia@.avansoft.com> schrieb im Newsbeitrag
> news:OZDxaTydFHA.1684@.TK2MSFTNGP09.phx.gbl...
> > Hello. Can I make a report for example with all the columns and make a
> > program in asp.net in which the user can select the columns he wants to
> > see?
> >
> > Thanks.
> >
> >
>sql

Wednesday, March 28, 2012

How to create maintenance plan without Northwind and Pubs

When creating a new database maintenance plan, there are four
different sets of databases to select:
o All databases
o All system databases (master, model, and msdb)
o All user databases (all databases other than master, model, and
msdb)
o These databases ...
I think that the most useful choice would be "All user databases
(excluding Northwind and Pubs)". But there are no such choice. Why?
How can I exclude the two demo databases from "user databases"? I know
I can delete them or mark them offline, but do I have to? I still want
to use them sometimes and therefor keep online.
So far I have used the "These databases" choice but it's sometimes
hard to keep track of all new and deleted (and offlined) databases.
The "All user databases (excluding Northwind and Pubs)" would be a
perfect solutions.
If I backup all user databases INCLUDING Northwind and Pubs, how can I
make some kind of trigger to detect a new backup file on disk and
delete it? The deletion should occur before the file would be written
to tape.
MarkkuAnswering on your last paragraph.
You can add one more CmdExec step to the backup job:
if exist c:\backup\pubs*.bak del c:\backup\pubs*.bak
if exist c:\backup\Northwind*.bak del c:\backup\Northwind*.bak
Bart Simpson
On 2 Mar 2004 01:25:24 -0800, google@.netti.fi (Markku Vainio) wrote:
>When creating a new database maintenance plan, there are four
>different sets of databases to select:
> o All databases
> o All system databases (master, model, and msdb)
> o All user databases (all databases other than master, model, and
>msdb)
> o These databases ...
>I think that the most useful choice would be "All user databases
>(excluding Northwind and Pubs)". But there are no such choice. Why?
>How can I exclude the two demo databases from "user databases"? I know
>I can delete them or mark them offline, but do I have to? I still want
>to use them sometimes and therefor keep online.
>So far I have used the "These databases" choice but it's sometimes
>hard to keep track of all new and deleted (and offlined) databases.
>The "All user databases (excluding Northwind and Pubs)" would be a
>perfect solutions.
>If I backup all user databases INCLUDING Northwind and Pubs, how can I
>make some kind of trigger to detect a new backup file on disk and
>delete it? The deletion should occur before the file would be written
>to tape.
>Markku|||Bart Simpson <bartsimpson000@.yahoo.com> wrote in message news:<jvk940d4b2nrqud5gtn0bk2gjnfusgc96f@.4ax.com>...
> Answering on your last paragraph.
> You can add one more CmdExec step to the backup job:
> if exist c:\backup\pubs*.bak del c:\backup\pubs*.bak
> if exist c:\backup\Northwind*.bak del c:\backup\Northwind*.bak
Thanks for your thoughts, but my Enterprise Manager says, that "It is
not recommended that jobs created by the maintenance plan be modified
in any way." I think there are a good reason for this.
It seems that there isn't any good solution for the demo database
backup maintenance problem. I think it would be best to just avoid
using the "All user databases" choice. Selecting all needed databases
one by one is the safest choice.
Markku|||I always delete the demo databases from production machines. Why do you want
to litter the machine with those databases? IF you need it for some test or
so, you can always create them from the script files.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
"Markku Vainio" <google@.netti.fi> wrote in message
news:2a683d86.0403050940.4022d634@.posting.google.com...
> Bart Simpson <bartsimpson000@.yahoo.com> wrote in message
news:<jvk940d4b2nrqud5gtn0bk2gjnfusgc96f@.4ax.com>...
> > Answering on your last paragraph.
> > You can add one more CmdExec step to the backup job:
> >
> > if exist c:\backup\pubs*.bak del c:\backup\pubs*.bak
> > if exist c:\backup\Northwind*.bak del c:\backup\Northwind*.bak
> Thanks for your thoughts, but my Enterprise Manager says, that "It is
> not recommended that jobs created by the maintenance plan be modified
> in any way." I think there are a good reason for this.
> It seems that there isn't any good solution for the demo database
> backup maintenance problem. I think it would be best to just avoid
> using the "All user databases" choice. Selecting all needed databases
> one by one is the safest choice.
> Markku|||"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in message news:<OQSfbpuAEHA.628@.TK2MSFTNGP10.phx.gbl>...
> I always delete the demo databases from production machines. Why do you want
> to litter the machine with those databases? IF you need it for some test or
> so, you can always create them from the script files.
Actually deleting the demo db's is the most straightforward idea. I
didn't earlier know how they can be rebuilt so I didn't want to lose
them ;-). Now I know. Thanks!
Markku

Monday, March 26, 2012

how to CREATE duplicate rows

this may sound like a weird one, but i need to create duplicates of all rows that satisfy a condition.

using asp, i am able to select rows from a databate using a recordset, only to insert it straight back into the database, thus assigning it a new unique id.

but is there any one to perform this action just using sql?

thanks,

goran.insert your_table
select * from your_table x
inner join (
select field_you_want_to_have_duplicates_on, cnt=count(*)
from your_table group by field_you_want_to_have_duplicates_on
having count(*) > 1) y
on x.field_you_want_to_have_duplicates_on = y.field_you_want_to_have_duplicates_on|||I think I just heard their head explode...

They want to do it from asp...that's a pure sql solution (which is the fastest btw)

Just loop through you're rs and do an insert for every iteration...|||i will disagree
if they truly wanted to do it from asp, why did they come to the sql forum??

they want sql and they know it!! and there's no denying

isnt that right rdjabarov?
rd? rd... RD!
well he HAD my back on this..|||AAAAAAAAAAAAAAAAAAAAAAAAAAAARRRRRRRRRRHHHHHHHH!!!

I'm on 2 conf calls and typing here|||hmmm ... i think you guys got me wrong, my current solution is implemented in asp using the same method that me and you have described. i was seeking a pure SQL solution.

anyway, thanks for replying, i've tried adapting your sql statement to my tables but am not getting very far. let me explain a little further ...

i have a table called 'tblWinesEnPrimeur' and want to make a duplicate of every row in this table that has a 'SectionID' of 21.

thanks,
goran.|||Simply remove all your primary keys and constraints, and your users will surely create the duplicate records for you.|||Originally posted by blindman
Simply remove all your primary keys and constraints, and your users will surely create the duplicate records for you.

Very helpful...

I'm betting you have an IDENTITY Column...ket's say Col1

INSERT INTO tblWinesEnPrimeu (Col2, Col3, Col4, ect)
SELECT Col2, Col3, Col4, ect)
FROM tblWinesEnPrimeu
WHERE SectionId = 21

Without the DDL it's a guess...|||I'd suggest using:INSERT INTO yourTable (collist)
SELECT *
FROM yourTable
WHERE 21 = sectionIdTHis should massively confuse your data, and make the users very happy!

-PatP|||sorry guys, no luck with that either, it's on the client's server and we have no direct access to the database, also the website was orignally designed so that duplicates are not inserted by front-end users of the site.

the sql threw up the same exception as before, simple 'Object required'. like i said it's all workin using the asp/sql combined solution, but the client prefers straight forward sql scripts rather than asp pages which can be run many times and inflate or alter the database.|||I give up...I'm totally lost...

Maybe if you post some (any) code, it might help...|||I'll second that thought! I'd suggest that you use SQL Enterprise Mangler to script everything about that table, the DDL, the indicies, even the permissions. Given that and the nickel description that you posted above, I'll bet that one of us can work out the solution!

-PatP|||insert your_table
select * from your_table x
inner join (
select field_you_want_to_have_duplicates_on, cnt=count(*)
from your_table group by field_you_want_to_have_duplicates_on
having count(*) > 1) y
on x.field_you_want_to_have_duplicates_on = y.field_you_want_to_have_duplicates_on
where x.SectionID = 21

Friday, March 23, 2012

how to create database diagram

i have a problem when i want to create diagram. i'll right clik and select add existing table and the box table appear but when i select table and clik button add the message error appear "CoInitialize has not been canceled". what the hell going on. pls help me out. i'm using msql 7.0even i am facing the same problem...can somebody help me on this

Tom

How to create an update or delete method in a strongly typed dataset?

Like the subject says, I'm using strongly typed datasets. I'm using to designer to create the datasets and the methods. I can select and insert, but I can't update or delete.

I right click on the adapter bar and select Add Query.

I sleect 'Use SQL Statements'

I select 'Update' (or 'Delete')

I get a sql statement pane containing the word 'Update' ('Delete') and asking 'What data should the table load?'

I can click on next, but anything else gives me errors. I'd list them, but I'm clearly doing something wrong and it's probably obvious.

Diane

Have you made sure that you have set a primary key for your table.|||

The table didn't have a primary key. I added one, but I still don't know how I'm supposed to use update and delete in a recordset.

Diane

|||

Hi Diane,

You can remove and re-add the TableAdapter. Set the SELECT command to select from that table which has primary key.

When you walk to the end of the wizard, it will show you that Update and Delete methods are generated. In this case, you will be able to Update and Delete through the TableAdapter.

|||

Update and Delete have been generated, I just don't know how to use them.

Diane

|||

Hi Diane,

When you have generated the Update and Delete methods, you can call them directly from an instance of TableADapter.

The Update method has several overloads. Some take a DataRow or a DataSet. They can update rows in batch. There is another overload that takes each field value seperately.

The Delete method takes arguments for all the field values, and it will check then delete the row.

HTH. If this does not answer your question, please feel free to mark the post as Not Answered and reply. Thank you!

Wednesday, March 21, 2012

How to create a table (structure) based on a result of a stored procedure

following statement will not work ..SELECT * INTO #xxx FROM (EXECUTE
sp_storedprocedure)
instead of select you can use INSERT INTO will work
eg:
create table #t(i int)
insert into #t exec myproc
create proc myproc
as
select 1
vinu
"Andrew Drake" <andrewdrake@.hotmail.com> wrote in message
news:ueWGWKyAHHA.1012@.TK2MSFTNGP04.phx.gbl...
> Dear all,
> There is a stored procedure that returns a result set consisting of some
> 30
> columns of different types.
> How can I automatically (i.e. not by means of CREATE TABLE statement)
> create
> a table with a structure that correspons to the returned result set?
> I mean something like:
> SELECT * INTO #xxx FROM (EXECUTE sp_storedprocedure)
> (The above unfortunately doesn't work).
> To be specific: the stored procedure in question is:
> sp_MSenum_replication_agents @.type = 4, @.exclude_anonymous = 1
> Any help would be greatly appreciated!
> Thank you in advance.
> Best regards,
> Andrew
>
Well .. it is not possible to use select into...exec
vt
"Andrew Drake" <andrewdrake@.hotmail.com> wrote in message
news:OXdJJayAHHA.4328@.TK2MSFTNGP03.phx.gbl...
> As I wrote, the idea is to create the table automatically, i.e. NOT to use
> the CREATE TABLE statement.
> Best regards,
> Andrew
>
> "vt" <vinu.t.1976@.gmail.com> wrote in message
> news:%23GSuhRyAHHA.4672@.TK2MSFTNGP02.phx.gbl...
>
sql

How to create a table (structure) based on a result of a stored procedure

Andrew

> SELECT * INTO #xxx FROM (EXECUTE sp_storedprocedure)
> (The above unfortunately doesn't work).
No , you have to know how many "columns" stored procedures will be returned
insert into tablename exec sp
"Andrew Drake" <andrewdrake@.hotmail.com> wrote in message
news:ueWGWKyAHHA.1012@.TK2MSFTNGP04.phx.gbl...
> Dear all,
> There is a stored procedure that returns a result set consisting of some
> 30
> columns of different types.
> How can I automatically (i.e. not by means of CREATE TABLE statement)
> create
> a table with a structure that correspons to the returned result set?
> I mean something like:
> SELECT * INTO #xxx FROM (EXECUTE sp_storedprocedure)
> (The above unfortunately doesn't work).
> To be specific: the stored procedure in question is:
> sp_MSenum_replication_agents @.type = 4, @.exclude_anonymous = 1
> Any help would be greatly appreciated!
> Thank you in advance.
> Best regards,
> Andrew
>
Andrew
Well, in that case take a look into dynamic sql
"Andrew Drake" <andrewdrake@.hotmail.com> wrote in message
news:u7PBTayAHHA.4328@.TK2MSFTNGP03.phx.gbl...
> Dear Uri,
> As I wrote, the idea is to create the table automatically, i.e. NOT to use
> the CREATE TABLE statement.
> Best regards,
> Andrew
> "Uri Dimant" <urid@.iscar.co.il> wrote in message
> news:esBsGPyAHHA.3536@.TK2MSFTNGP03.phx.gbl...
>
|||Andrew
--This procedure returns three or two columns from Orders Table depends on
parameter
create proc usp_test
@.orderid int =10248
as
if @.orderid=10248
select orderid,orderdate from orders where orderid=@.orderid
else
select orderid,orderdate,CustomerID from orders where orderid=@.orderid
--I use OPENROWSET command to run this SP and get the data out to temporary
table
select * into #t
from
openrowset('SQLOLEDB','SERVER=NT_SQL_4;DATABASE=No rthwind;UID=appdev;PWD=np,jho;',
'set fmtonly off; exec usp_test 10249') as p
select * from #t
drop table #t
"Andrew Drake" <andrewdrake@.hotmail.com> wrote in message
news:OzpHB2yAHHA.1220@.TK2MSFTNGP04.phx.gbl...
> Dear Uri,
> Thank you for the hint. If I understand you correctly, you suggest that I
> should CREATE TABLE dynamically (EXEC ('CREATE TABLE...')).
> That's OK, but how can I get (programmatically) the list of "columns" that
> are returned by the stored procedure?
> My basic question is
> So, the situation is as follows: I have got a stored procedure and want to
> put its result set into a new table.
> Something like SELECT * INTO MyNewTable FROM ExistingTableOrView,
> but instead of ExistingTableOrView there is a stored procedure.
> Best regards,
> Andrew
>
> "Uri Dimant" <urid@.iscar.co.il> wrote in message
> news:%23N7N5hyAHHA.5068@.TK2MSFTNGP02.phx.gbl...
>
>
|||> P.S. Isn't it a bit strange that we have to refer to our own SQL server
> via
> 'openrowset'?
:-)
"Andrew Drake" <andrewdrake@.hotmail.com> wrote in message
news:ezPsolzAHHA.3540@.TK2MSFTNGP03.phx.gbl...
> Dear Uri,
> Great! It works!
> Thank you very much for your help!
> Best regards,
> Andrew
> P.S. Isn't it a bit strange that we have to refer to our own SQL server
> via
> 'openrowset'?
>
> "Uri Dimant" <urid@.iscar.co.il> wrote in message
> news:OboMuXzAHHA.5060@.TK2MSFTNGP02.phx.gbl...
>
>
|||Tibor
I did not want to create a linked server that OPENQUERY required unlike
OPENROWSET when you can reference to the server without having a linked
server
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:OfQkCm0AHHA.1224@.TK2MSFTNGP04.phx.gbl...
> OPENQUERY() is another option...
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>
> "Andrew Drake" <andrewdrake@.hotmail.com> wrote in message
> news:ezPsolzAHHA.3540@.TK2MSFTNGP03.phx.gbl...
>

How to create a select statement with an increasement variable?

Example:

Select icount + 1 as icount from table

or

Select counter() as icount from table

The above is wrong ...just a sample to show what I am trying to accomplish.

Is there a function in SQL statement? Thanks.No, this unfortunately is not possible.

The solution I've seen to this is to create either a #Temp table (or better, a table variable) with an Identity column and the other columns you need, and then INSERT your resultset into it. This will give you the incrementing column you are looking for.

Alternately, add this counter in the front end (on your ASP.NET page).

Terri|||The reason I can't add the counter in the front end because I am doing paging.

Thanks for your help. I think I will create #temp table to solve my problem.sql

Monday, March 19, 2012

How to create a spread sheet from a sql table results?

I have to run a simple query (say select name from table where id = 4) and get those results and make it into a report. I am not sure I have crystal reports (do I have to install some thing for this?). So what is the easiest way to create this? May in in a spread sheet or some thing like this? I am so new to SQL Server

Thanks

Possible way:

Retrieve data in DataSet
|||

Hi dotnet001,

Of course you can use Crystal reports to generate that report. But since you have mentioned that you want the "easiest" way and "may in a spead sheet", I think maybe you can try the DataGrid control. You can fist connect to the database and execute the sql query string,then call the databind method of the DataGrid control to retrieve data from the query result set. After that you will have a detailed list which show all the items you get from that database.

I would like to suggest you to read something on ADO.NET and databinding. See:http://www.w3schools.com/aspnet/aspnet_databinding.asp (tutorial)

http://www.codeproject.com/aspnet/Mastering_DataBinding.asp (code example)

Hope my suggestion can help

This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.

How to create a select statement with an increasement variable?

Example:

Select icount + 1 as icount from table

or

Select counter() as icount from table

The above is wrong ...just a sample to show what I am trying to accomplish.

Is there a function in SQL statement? Thanks.No, this unfortunately is not possible.

The solution I've seen to this is to create either a #Temp table (or better, a table variable) with an Identity column and the other columns you need, and then INSERT your resultset into it. This will give you the incrementing column you are looking for.

Alternately, add this counter in the front end (on your ASP.NET page).

Terri|||The reason I can't add the counter in the front end because I am doing paging.

Thanks for your help. I think I will create #temp table to solve my problem.

How to create a Recordset that joins 3 temp tables

I have an stp where I want to return a Recordset via a SELECT that joins 3 temp tables...

Here's what the temp tables look like (I am being brief)...

CREATE TABLE #Employees (EmpID INTEGER, EmpName NVARCHAR(40))

CREATE TABLE #PayPeriods (PayPeriodIndex INTEGER, StartDate DATETIME, EndDate DATETIME)

CREATE TABLE #Statistics (EmpID INTEGER, PayPeriodIndex INTEGER, HoursWorked REAL)

The #Employees table is populated for all employees.

The #PayPeriods table is populated for each calandar week of the year (PayPeriodIndex=0 to 51).

The #Statistics table is populated from data within another permanent table.

Some employees do not work all 52 weeks.

Some employees do not work any of the 52 weeks.

So, the #Statistics table doesn't have all possible combinations of Employees and PayPeriods.

I want to return a Recordset for all possible combinations of Employees and PayPeriods...

Here's a SELECT that I have used...

SELECT e.EmpId, e.Name, pp.PayPeriodIndex, ISNULL(s.HoursWorked,0)

FROM #Statistics s

LEFT OUTER JOIN #Employees e....

LEFT OUTER JOIN #PayPeriods pp ....

WHERE s.EmpId = e.EmpId

AND s.PayPeriodIndex = pp.PayPeriodIndex

I have had no luck with this SELECT.

Can anybody help?

TIA

I think this is what you want

SELECT e.EmpId, e.EmpName, pp.PayPeriodIndex, ISNULL(s.HoursWorked,0)
FROM #Employees e
CROSS JOIN #PayPeriods pp
LEFT OUTER JOIN #Statistics s
ON e.EmpID = s.EmpID
AND s.PayPeriodIndex = pp.PayPeriodIndex

If you want all employess and all pay periods - you should base your query on the employee table and cross join it to the payperiods table - that should give you all employees and all possible pay period combos.

then you should left outer join to the Stats table to get the hours worked if they exist.

Thanks

AWAL

|||

AWAL,

Thanks alot for your response

I tried the Cross Join and Left Outer Join and I am now generasting the correct recordset...

Thanks again!!!

Dan

|||

There is a lot going on with this report. I can definitely see the solution using the CROSS and LEFT joins; however, I ask the following questions:

When I run this with pay periods that are for future dates I get the future pay periods on the report -- is that wanted?|||

Maybe my questions are off-base. Please forgive me for muddying the water here.

Dave

Monday, March 12, 2012

How to create a new Backup device?

How do I create a new Backup device in SQL Server 2005? When I invoke "Back
Up..." from Management, I only get the option to select a file path (under
Select Backup Destionation). The option to select a Backup device is empty
and greyed out.
OlavYou need to create the backup device first. This is under the "Server Objects" folder, or use
sp_addumpdevice directly.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Olav" <x@.y.com> wrote in message news:%234EW0V$WGHA.5012@.TK2MSFTNGP05.phx.gbl...
> How do I create a new Backup device in SQL Server 2005? When I invoke "Back Up..." from
> Management, I only get the option to select a file path (under Select Backup Destionation). The
> option to select a Backup device is empty and greyed out.
> Olav
>

How to create a new Backup device?

How do I create a new Backup device in SQL Server 2005? When I invoke "Back
Up..." from Management, I only get the option to select a file path (under
Select Backup Destionation). The option to select a Backup device is empty
and greyed out.
OlavYou need to create the backup device first. This is under the "Server Object
s" folder, or use
sp_addumpdevice directly.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Olav" <x@.y.com> wrote in message news:%234EW0V$WGHA.5012@.TK2MSFTNGP05.phx.gbl...reen">
> How do I create a new Backup device in SQL Server 2005? When I invoke "Bac
k Up..." from
> Management, I only get the option to select a file path (under Select Back
up Destionation). The
> option to select a Backup device is empty and greyed out.
> Olav
>

how to create a dynamic view?

Is there a way to create a dynamic view, that will read the current month and select records in table for the last 12 months?

thanks

Something like this should work for you: This will alway provide the data for the previous twelve months up to the moment of execution.

Code Snippet


CREATE TABLE MyTable
( RowID int IDENTITY,
DateCol datetime,
)
GO


CREATE VIEW MyView
AS
SELECT
RowID,
DateCol
FROM MyTable
WHERE DateCol >= ( dateadd( month, -12, getdate() ) )
GO


SET NOCOUNT ON


INSERT INTO MyTable VALUES ( '02/15/2006' )
INSERT INTO MyTable VALUES ( '03/01/2006' )
INSERT INTO MyTable VALUES ( '04/01/2006' )
INSERT INTO MyTable VALUES ( '03/15/2006' )
INSERT INTO MyTable VALUES ( '02/28/2006' )
INSERT INTO MyTable VALUES ( '02/15/2007' )
INSERT INTO MyTable VALUES ( '03/01/2007' )
INSERT INTO MyTable VALUES ( '04/01/2007' )
INSERT INTO MyTable VALUES ( '03/15/2007' )
INSERT INTO MyTable VALUES ( '02/28/2007' )


SELECT *
FROM MyView
ORDER BY DateCol DESC


DROP TABLE MyTable
DROP VIEW MyView

|||You could do something along the lines of the following:

CREATE VIEW YourLastTwelve
AS
SELECT *
FROM YourTable
WHERE YourDateField < CONVERT(varchar(25),
DATEADD(m, 1, GetDate() + 1 - DAY(GetDate())), 101)
AND YourDateField >= CONVERT(varchar(25), DATEADD(yy, -1 ,
DATEADD(m, 1, GetDate() + 1 - DAY(GetDate()))), 101)

-Sue

Friday, March 9, 2012

how to create a dynamic Select statements in my C# project

hi, can someone teach me how to create a dynamic Select statements in my C#
project.
i have this sets of select statements that will return the table name and
fields...and that table name and fields are the one im going to use to
create my dynamic select statements...how can i do this'
thanksProbably the best answer is Don't! In a well-designed business process
application Dynamic SQL is rarely necessary and not often a good idea.
Dynamic SQL is bad news for many reasons to do with performance, security an
d
maintainability. The best practice in a tiered architecture is usually to
build data access code in stored procedures and views and then use
parameterized procedures as your application's entry point to the database.
If you are building a general purpose database admin tool then you might
want to consider putting dynamic code in your application, in which case you
would probably want to use the .Net SqlCommand class. Otherwise you may want
to come back with a bit more information about your requirements so that
someone can advise you better.
David Portas
SQL Server MVP
--|||If your question is about generating dynamic SQL statements using
Transact-SQL, see http://www.sommarskog.se/dynamic_sql.html for a
discussion.
To generate dynamic SQL in application code, simply build a string
containing the needed SQL statement and execute using one of the
System.Data.SqlClient objects. Use command parameters as needed.
Hope this helps.
Dan Guzman
SQL Server MVP
"cEciLlE" <cecille.regidor@.gmail.com> wrote in message
news:eHeK54rLFHA.3296@.TK2MSFTNGP15.phx.gbl...
> hi, can someone teach me how to create a dynamic Select statements in my
> C# project.
> i have this sets of select statements that will return the table name and
> fields...and that table name and fields are the one im going to use to
> create my dynamic select statements...how can i do this'
>
> thanks
>

Wednesday, March 7, 2012

How to count rows in this query...

SELECT ID_AnagraficaRivendita
FROM dbo.AnagraficaRivendite
WHERE EXISTS
(SELECT *
FROM dbo.Flussi_Rivendite
WHERE dbo.Flussi_Rivendite.CodiceProdotto = 631 AND dbo.AnagraficaRivendite.ID_AnagraficaRivendita = dbo.Flussi_Rivendite.ID_AnagraficaRivendita)
AND EXISTS
(SELECT *
FROM dbo.Flussi_Rivendite
WHERE dbo.Flussi_Rivendite.CodiceProdotto = 615 AND dbo.AnagraficaRivendite.ID_AnagraficaRivendita = dbo.Flussi_Rivendite.ID_AnagraficaRivendita)
GROUP BY ID_AnagraficaRivendita

hi, in this query (in which I extract all ID_AnagraficaRivendita who have a correspondence in table Flussi_Rivendite with CodiceProdotto = 631 AND CodiceProdotto = 615), I would like to receive also a count of extracted rows... have you any idea?? Thank you ;)

There are so many ways like using COUNT(). But I always prefer usingROW_NUMBER()

e.g.

SELECT ROW_NUMBER()OVER (ORDER BY ID_AnagraficaRivenditaASC)AS Row, ID_AnagraficaRivenditaFROM dbo.AnagraficaRivenditeWHEREEXISTS(SELECT *FROM dbo.Flussi_RivenditeWHERE dbo.Flussi_Rivendite.CodiceProdotto = 631AND dbo.AnagraficaRivendite.ID_AnagraficaRivendita = dbo.Flussi_Rivendite.ID_AnagraficaRivendita)AND EXISTS(SELECT *FROM dbo.Flussi_RivenditeWHERE dbo.Flussi_Rivendite.CodiceProdotto = 615AND dbo.AnagraficaRivendite.ID_AnagraficaRivendita = dbo.Flussi_Rivendite.ID_AnagraficaRivendita)GROUP BY ID_AnagraficaRivendita
|||

try this (it was not tested but it should give you idea if it will not work)

SELECT ID_AnagraficaRivendita, FL.CodiceProdotto,count(*) Counter

FROM dbo.AnagraficaRivendite

LeftjoinFROM dbo.Flussi_Rivendite FL

ON dbo.AnagraficaRivendite.ID_AnagraficaRivendita= FLID_AnagraficaRivendita

and FL.CodiceProdottoin(631,615)

wherenot FL.CodiceProdottoisnull

groupby ID_AnagraficaRivendita, FL.CodiceProdotto

|||

Thank you for your reply, I have added ROW_NUMBER()OVER (ORDER BY ID_AnagraficaRivenditaASC)AS Row but it doesn't work, I receive an error (ADO Error: ROW_Number is not a valid function)

I don't know if is important: I am working on Sql Server 2000 and my query is in a Stored Procedure.

|||

RETURN @.@.ROWCOUNT

http://msdn2.microsoft.com/en-us/library/ms187316.aspx

|||

row_number is new in SQL 2005, not available in SQL 2000

|||

At my home pc I have just tried instruction ROW_NUMBER on SQL Server 2005 and it runs, but maybe my question it was not clear, sorry: I need TOTAL of extracted rows, on the contray with ROW_NUMBER I receive a progressive numeration of record (if it's possible, please suggest me a solution compatible on SQL Server 2000, tooStick out tongue)

|||

Change your stored procedure into this:

SELECTCOUNT(ID_AnagraficaRivendita)AS TotalRows, ID_AnagraficaRivenditaFROM dbo.AnagraficaRivenditeWHEREEXISTS(SELECT *FROM dbo.Flussi_RivenditeWHERE dbo.Flussi_Rivendite.CodiceProdotto = 631AND dbo.AnagraficaRivendite.ID_AnagraficaRivendita = dbo.Flussi_Rivendite.ID_AnagraficaRivendita)AND EXISTS(SELECT *FROM dbo.Flussi_RivenditeWHERE dbo.Flussi_Rivendite.CodiceProdotto = 615AND dbo.AnagraficaRivendite.ID_AnagraficaRivendita = dbo.Flussi_Rivendite.ID_AnagraficaRivendita)GROUP BY ID_AnagraficaRivendita

Howevere let me also tell you thatthis is not at all an elegant solution. If you know how to work with return values, I suggest you addRETURN@.@.ROWCOUNT at the end of your original query, as suggested by DisturbedBuddha.

~

|||

thanks my friends Wink

Friday, February 24, 2012

How to copy table in SQL Server 2000?

I want to make an exact copy of a table in SQL Server 2000.
If I right click on the table I can select copy, but paste does not show up?Hi

You're probably better off right clicking the database itself (in Enterprise Manager), and selecting All Tasks | Import Data. Even though the data source and destination are the same, you can make it copy to a table with a new name. When you get to the list of available tables, check the one you want then alter the destination to a new name - click on transform to get an idea of what's going on.
I find that I need to setup my identities and keys again, but otherwise works well.

An alternative would be to copy the table as you've done, then use the above to pull data into it (or an insert statement).|||How about just "select * into new_table from old_table"?|||rd is exactly right that syntax would do... 'Select * INTO'|||I was able to do it that way. I was wondering if there is an easy way to just copy and paste - similar to how you would do it in access.
I guess I don't understand why you can copy a table but not paste it.|||When you right-click copy a table name in Enterprise Manager, you are only copying the table design. If you go to your Query Analyzer window and paste, you will see the create table statement for that table. This is functionally equivalent to right-clicking on the table in the Query Analyzer object browser and choosing "Script object to Clipboard As >> Create."|||Be aware that "select * into new_table from old_table" does not make an exact copy of the TABLE. It makes an exact copy of the DATA. Any indexes, foreign keys, or triggers associate with the table will not be created.|||i think the effective question is the one we always end up asking

What do you want to copy a table for ?
or
what are you trying to do and maybe we can help you find an easier way to do it.

Sunday, February 19, 2012

How to copy query result to a label?

Hi,

I want to run a select query and copy the result to a label. I created a SqlDataSource1, but I don't know how to go ahead.

I would like to do something like:

string x = SqlDataSource1.SelectCommand

Please, advice!

label takes values of 1D. Your SQL results are 2D. How do you expect to bind them together? You would need a data control such as datagrid/gridview etc.

|||The same way most people would think -- assume your talking about the first row always. Unfortunately ASP.NET is a pain that way -- You have to bind the datasource to a control that understands row traversing first (Even if your query only returns one row, which is stupid), place all your labels within that control, and then you can bind them to a particular column.