Question : How to use table variable for input parameter

Hi,

I'm trying to do something like the following which doesn't work:

select *
from table1
where Col1 in (@list)

I basically have a stored procedure which accepts a parameter that can be a comma delimited list of IDs, eg:
'1,2,3,4'

I don't want to use dynamic sql but rather use a table variable and then doing a join on the table variable. But I'm not sure how to parse the list of values into the table variable. How can this be done?

Thanks

Answer : How to use table variable for input parameter

You can use the function below to create the table you need
based on the comma-separated values you have.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
create function fn_MySplit(
 @String nvarchar (4000)
 )
returns @ValueTable table ([Value] nvarchar(4000))
begin
 declare @NextString nvarchar(4000)
 declare @Pos int
 declare @NextPos int
 declare @Delimeterer nvarchar(1)
 declare @CommaCheck nvarchar(1)
 
 --Initialize
 set @NextString = ''
 set @Delimeter = ','
 set @CommaCheck = right(@String,1) 
 
 --Check for trailing Comma, if not exists, INSERT
 if (@CommaCheck <> @Delimiter )
  set @String = @String + @Delimiter
 
 --Get position of first Comma
 set @Pos = charindex(@Delimiter,@String)
 set @NextPos = 1
 
 --Loop while there is still a comma in the String of levels
 while (@pos <>  0)  
 begin
  set @NextString = substring(@String,1,@Pos - 1)
 
  insert into @ValueTable ( [Value]) Values (@NextString)
 
  set @String = substring(@String,@pos +1,len(@String))
  
  set @NextPos = @Pos
  set @pos  = charindex(@Delimiter,@String)
 end
 
 return
end
Random Solutions  
 
programming4us programming4us