November 16, 2004 at 9:17 am
Hi,
I am trying to write a stored procedure to select a recordset. However, I need to be able to change the WHERE clause of the procedure depending on the value of one of the parameters. I tried something like the following but obviously it doesn't work. What is the correct way to do it?
CREATE PROCEDURE ListMyTable( @Op As Integer, @ParamValue As Integer)
AS
SELECT TABLE_ID FROM MY_TABLE
IF @Op = 1
WHERE COL1 = @ParamValue
ELSE IF @Op = 2
WHERE COL2 = @ParamValue
GO
November 16, 2004 at 9:51 am
CREATE PROCEDURE ListMyTable( @Op As Integer, @ParamValue As Integer)
AS
IF @Op = 1
select table_id from mytable WHERE COL1 = @ParamValue
ELSE IF @Op = 2
select table_id from mytable WHERE COL2 = @ParamValue
GO
November 16, 2004 at 9:55 am
Thanks for that Steve.
Unfortunately my SELECT prodcedure is much more complicated than the one illustrated. The reason I'm doing this is that I don't want to have to maintain multiple column lists as this is a nightmare to maintain. Is there a way to do it with one SELECT procedure and tack the WHERE clause on afterwards?
November 16, 2004 at 11:50 am
try this out in query analyzer(it doesn't paste well in the thread)....
declare @op int
declare @paramvalue int
(set variables to a value for test)
declare @sql_script varchar(2000)
set @sql_script='select table_id from my_table where col'+@op+' ='+@paramvalue+''
exec (@sql_script)
November 16, 2004 at 1:23 pm
See, if this helps:
http://www.sommarskog.se/dyn-search.html
http://www.sommarskog.se/dynamic_sql.html
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
November 16, 2004 at 3:33 pm
Hi,
Why don't you use:
WHERE
(@Op = 1 AND COL1 = @ParamValue)
OR
(@Op = 2 AND COL2 = @ParamValue)
November 16, 2004 at 11:54 pm
I had some very good luck using a CASE statement in a WHERE clause for just this purpose. Try something like this...
AS
SELECT TABLE_ID
WHERE 1 = CASE ---- CASE "TESTS" RUN IN ORDER LISTED
--Jeff Moden
Change is inevitable... Change for the better is not.
November 17, 2004 at 2:32 am
Thanks for all the excellent replies. In the end I had the most success with Jeff's approach.
Thanks again!
November 17, 2004 at 9:03 am
I've used a twist on the above use of CASE for controlling the WHERE clause depending on the values of input parameters. Something like:
SELECT *
FROM MyTable
WHERE Col1 = CASE @Parameter1
WHEN 1 THEN 'A'
WHEN 2 THEN 'B'
ELSE 'Other' END
You could modify how you use the CASE to accomodate ranges and more complex logic.
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply