November 24, 2008 at 7:22 am
I have a stored procedure such as this;
select name, center, region, customer
from tbl1 where center = @center and state =@state
My question is, on the web form, State can be passed as a single state id (1) or such as
state = 1,2,3,4,5,6,7, and so on.
Within the stored procedure, how can I accomodate the ( , ) in the string and handle it on the DB side instead of having the developer calling the database for each state being passed in?
so the query could look like:
select name, center, region, customer
from tbl1 where center = @center and state = 1
or
select name, center, region, customer
from tbl1 where center = @center and state = 1,2,3,4,5,6,7,8,
November 24, 2008 at 7:42 am
I use xml in order to aviod having to use dynamic sql. This should explain how you would use both.
November 24, 2008 at 7:57 am
I got that to work within my normal query, how would this work in a pivot query?
November 24, 2008 at 7:59 am
Hi,
I am a fairly new DBA but what about this:
DECLARE @sqlStmt varchar(8000)
SELECT @sqlStmt = 'select name, center, region, customer
from tbl1 where center = ' + @center + ' and state IN (' + @state + ')'
EXEC (@sqlStmt)
November 24, 2008 at 8:02 am
I have that working, I'm trying to get it to work within my query that is doing a pivot.
here is my pivot query:
SELECT *
FROM (
'SELECT tblCustomer.CusterName, tblCustomer.Date as TotalSales, tblMAIN.Region
FROM tblCustomer INNER JOIN
tblOrders ON tblCustomer.CustID = tblOrders.CustID
where
tblOrders.State IN (' + @State + ') and
tblOrders.[Date]
BETWEEN
COALESCE(NULLIF(@StartDate,''),tblOrders .[Date])
AND
COALESCE(NULLIF(@EndDate,''),tblOrders .[Date])'
) AS D
PIVOT
(
Count(TotalSales)
For Region
IN ([NE], [SE], [SW], [NW])
)
AS P
November 24, 2008 at 9:06 am
Without having the tables etc to test this against this should be pretty much there:
This would encapsulate all the code into the variable then run it as a complete statement instead of trying to nest the select.
Another alterntaive woulb be to have the nested part as a function and join the results to the function.
DECLARE @sqlstmt varchar(8000)
'SELECT *
FROM (
SELECT tblCustomer.CusterName, tblCustomer.Date as TotalSales, tblMAIN.Region
FROM tblCustomer INNER JOIN
tblOrders ON tblCustomer.CustID = tblOrders.CustID
where
tblOrders.State IN (' + @State + ') and
tblOrders.[Date]
BETWEEN
COALESCE(NULLIF(@StartDate, '+ '''' + '''' +' ),tblOrders .[Date])
AND
COALESCE(NULLIF(@EndDate,'+ '''' + '''' +'),tblOrders .[Date])
) AS D
PIVOT
(
Count(TotalSales)
For Region
IN ([NE], [SE], [SW], [NW])
)
AS P'
EXEC (@sqlStmt)
November 24, 2008 at 9:08 am
Forgot that you can also test the output statment by replacing the "EXEC (@sqlStmt)" command with "PRINT (@sqlStmt)" . This output can then be copied to queryanlyser to run independantly to verify syntax etc.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply