1

I have a stored procedure that take many input parameters including an @userID.

Now, in the core of the SP I select from a view using the following Where close :

Where userID = @userID

This works fine. Now I want to pass multiple users to be able wo query it like this :

where userID in (1,2,...)

How can I pass the value 1,2 from one input parameter ?

Thanks

Sam Saffron
  • 128,308
  • 78
  • 326
  • 506
Joseph Ghassan
  • 759
  • 3
  • 9
  • 21
  • 2
    This has been asked SOOO many times on SO. You are aware that you can search other questions, and read their answers? – Adriaan Stander Oct 21 '10 at 05:03
  • @astander: good point. I answered without thinking... – Mitch Wheat Oct 21 '10 at 05:04
  • @astandar / @mitch a great approach here is to link to http://stackoverflow.com/questions/209686/passing-list-to-sql-stored-procedure or another canonical, so it shows up in the faq http://stackoverflow.com/tags/tsql/faq ... or update the wiki http://stackoverflow.com/tags/tsql/info to include it – Sam Saffron Oct 21 '10 at 05:22
  • why not passing the userID's in a table-variable, e.g.@TuserID. inside the sp you could do an inner join @TuserID on @TuserID.UserID = userID... – Ice Oct 22 '10 at 22:55

3 Answers3

1

Create a function split:

create FUNCTION [dbo].[Split]
(
       @List nvarchar(2000),
       @SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(

       Id int identity(1,1),
       Value nvarchar(2000)
)
AS
BEGIN

   While (Charindex(@SplitOn,@List)>0)
   Begin
           Insert Into @RtnValue (value)
           Select  Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1)))
           Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
   End

   Insert Into @RtnValue (Value)
           Select Value = ltrim(rtrim(@List))

           Return

--select Value from dbo.Split('item1, item2, item3',',')
END
GO

And call the function with @PASS and use it inside a cursor.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Vivek
  • 318
  • 1
  • 5
  • 17
0

Arrays and Lists in SQL Server

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
0

Create an input parameter which is a table varaible and send in the array as a table that you join to instead of using in. Read about this in BOL as it can be a little tricky to set up.

HLGEM
  • 94,695
  • 15
  • 113
  • 186