Groups | Blog | Home
all groups > sql server programming > february 2004 >

sql server programming : Dynamic "IN" clause or something better



Vishal Parkar
2/21/2004 2:12:33 PM
hi jimbo,

no need to use CASE simply put variable names in IN clause.See following example.
Ex:
use northwind
go

declare @x nchar(5)
declare @x1 nchar(5)
select @x='alfki',@x1=null
select * from customers
where customerid in(@x,@x1)

--
Vishal Parkar
vgparkar@yahoo.co.in


Roji. P. Thomas
2/21/2004 2:22:02 PM
Why Case?

You write something likethis in your sp

SELECT * From YourTable WHERE YourID IN(@id1, @id2, @id3)

and call your SP like

EXEC Test 1,655,NULL



--
Roji. P. Thomas
SQL Server Programmer
[quoted text, click to view]

Jimbo
2/21/2004 9:22:31 PM
Hi all.
New to this New Group, so forgive me if I ask the wrong wuestion inthe wrong
place.

I am porting an Access DB over to MSDE.
I build an SQL Statement in code then pass that to the Database.
As part of the process, it builds an "IN" clause based on some check boxes
the user selects, and this is then added the SQL variable which gets passed
to the DB.

The problem I have is, I cant just pass the "IN" clause i.e.( 1,2,3,4) as
part of the StoredProc variables, because I cant go :-

WHERE myfield='a'
AND myotherfield in (@INVar)

I then thought maybe I need to pass each variable (of which there can be a
max of 10) on its own, i.e.

@myvar1 int = null
@myvar2 int = null
@myvar3 int = null etc.etc.

Then use a CASE statement, i.e.
WHERE myfield='a'
AND myotherfield in (
CASE WHEN @MyVar1 IS NOT NULL then
1,
CASE WHEN @MyVar2 IS NOT NULL then
2,
)

But this didnt seem to work either.

Is there a nice or even un-nice way I can do this other than a Dynamic SQL,
because I had a problem with that too...hehe ;-)

Thanks, Jeremy

Jimbo
2/21/2004 10:03:18 PM
DOH !!! yeah thats a good way to do it !! It didnt even enter my
head....want an idiot.
Thanks heaps Vishal !!

Jeremy

[quoted text, click to view]

AddThis Social Bookmark Button