We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Stored Procedure Pass String Array for IN Clause

deadferret01
deadferret01 asked
on
Medium Priority
1,269 Views
Last Modified: 2008-11-17
Hi,

I am trying to figure out if it is possible to pass a string array ie.(1,2,3,4) into a stored procedure parameter ie (@sList)
so that I dont have to build a SQL string dynamically from my C# code.

It would work as follows:

my_stored_procedure_call '1,2,3,4'

CREATE PROCEDURE my_stored_procedure_call
      @sList            varchar(255)
AS
      SELECT name,detail
      FROM table
      WHERE id IN(CAST(@sList AS int))
GO

I continuously get "Error converting data type varchar to int". Has anyone ever been successful in doing this through a stored procedure.

Please note that the example above is extremely simple compared to what I am actually trying to query, but the concept is the exact same.

TIA
Comment
Watch Question

AneeshDatabase Consultant
CERTIFIED EXPERT
Top Expert 2009

Commented:
Database Consultant
CERTIFIED EXPERT
Top Expert 2009
Commented:
or use dynamic sql

CREATE PROCEDURE my_stored_procedure_call
     @sList          nvarchar(255)
AS
     declare @nSQL nvarchar(2000)
     SET @sSql = '
     SELECT name,detail
     FROM table
     WHERE id IN(' + REPLACE(@sList, '''','') +')'
     
     exec sp_executeSQL @sSQL  -- or EXEC (@sSQL)
GO

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Thank you very much! Worked perfectly.

Commented:
Perfect!

Just one thing, replace one line:
This
   declare @nSQL nvarchar(2000)
for
   declare @sSQL nvarchar(2000)

Thanks
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.