How to pass an array into a SQL Server stored procedure?
For example, I have a list of employees. I want to use this list as a table and join it with another table. But the list of employees should be passed as parameter from C#.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
SQL Server 2016 (or newer)
You can pass in a delimited list or
JSONand useSTRING_SPLIT()orOPENJSON().STRING_SPLIT():OPENJSON():I wrote more about this here:
SQL Server 2008 (or newer)
First, in your database, create the following two objects:
Now in your C# code:
SQL Server 2005
If you are using SQL Server 2005, I would still recommend a split function over XML. First, create a function:
Now your stored procedure can just be:
And in your C# code you just have to pass the list as
'1,2,3,12'…I find the method of passing through table valued parameters simplifies the maintainability of a solution that uses it and often has increased performance compared to other implementations including XML and string splitting.
The inputs are clearly defined (no one has to guess if the delimiter is a comma or a semi-colon) and we do not have dependencies on other processing functions that are not obvious without inspecting the code for the stored procedure.
Compared to solutions involving user defined XML schema instead of UDTs, this involves a similar number of steps but in my experience is far simpler code to manage, maintain and read.