January 13, 2009 at 2:08 pm
Hello All -
I'm having trouble figuring out the best way to handle a dynamic WHERE clause in a stored procedure. Below is what I'm trying to accomplish. The 3 commented out lines are what should be dynamic, based on the value of @Action. I tried a CASE, but had trouble getting it to work with IN (not =). For business reasons that don't apply to the procedure that I'm working on, I do need to be able to handle 9 values for @Action. 2 of them will actually change the results of the SELECT, the other 7 will just omit that filter, all returning the same results.
Thanks for the help!
DECLARE @Action char(1)
DECLARE @VendorID int
DECLARE @Count int
SET @Action = 'a'
SET @VendorID = 1
SELECT @Count = COUNT(DownloadID)
FROM dbo.tblDownload
WHERE VendorID = @VendorID
--AND DownloadStatusID IN (1,2) - @Action = a
--AND DownloadStatusID IN (3,4) - @Action = b
--omit this filter all together - @Action = c,d,e,f,g,h,i
AND DeltaDownloadID >
(
SELECT DeltaDownloadID
FROM tblDeltaDownloadTracking
WHERE VendorID = @VendorID
)
January 13, 2009 at 7:53 pm
Please try:
SELECT @Count = COUNT(DownloadID)
FROM dbo.tblDownload
WHERE VendorID = @VendorID
AND (@Action NOT IN (‘a’,’b’)
OR (@Action = ‘a’ and DownloadStatusID IN (1,2))
OR (@Action = ‘b’ and DownloadStatusID IN (3,4)) )
AND DeltaDownloadID >
( SELECT DeltaDownloadID
FROM tblDeltaDownloadTracking
WHERE VendorID = @VendorID )
January 14, 2009 at 3:22 am
I don't have any data to test on, but be careful... that looks an awful lot like a triangular join to me. For more info on why that could be a bad thing, please see the following...
http://www.sqlservercentral.com/articles/T-SQL/61539/
--Jeff Moden
Change is inevitable... Change for the better is not.
January 14, 2009 at 6:46 am
@Old Hand -
Thanks very much! That's a great solution.
@jeff -
I'd read that article once a long time ago. Thanks for reminding me about the problems with triangular joins. I have tons of test data in my dev and QA environments and I'll be sure to test that thoroughly with lots of rows. I’ll also have another developer here look at it.
Thanks again to both of you.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply