129

I am calling a SQL Server stored procedure from my C# code:

using (SqlConnection conn = new SqlConnection(connstring))
{
   conn.Open();
   using (SqlCommand cmd = new SqlCommand("InsertQuerySPROC", conn))
   {
      cmd.CommandType = CommandType.StoredProcedure;

      var STableParameter = cmd.Parameters.AddWithValue("@QueryTable", QueryTable);
      var NDistanceParameter = cmd.Parameters.AddWithValue("@NDistanceThreshold", NDistanceThreshold);
      var RDistanceParameter = cmd.Parameters.AddWithValue(@"RDistanceThreshold", RDistanceThreshold);

      STableParameter .SqlDbType = SqlDbType.Structured;
      NDistanceParameter.SqlDbType = SqlDbType.Int;
      RDistanceParameter.SqlDbType = SqlDbType.Int;

      // Execute the query
      SqlDataReader QueryReader = cmd.ExecuteReader();

My stored proc is fairly standard but does a join with QueryTable (hence the need for for using a stored proc).

Now: I want to add a list of strings, List<string>, to the parameter set. For example, my stored proc query goes like this:

SELECT feature 
FROM table1 t1 
INNER JOIN @QueryTable t2 ON t1.fid = t2.fid 
WHERE title IN <LIST_OF_STRINGS_GOES_HERE>

However, the list of strings is dynamic and a few hundred long.

Is there a way to pass a list of strings List<string> to the stored proc??? Or is there a better way to do this?

Many thanks, Brett

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Brett
  • 11,637
  • 34
  • 127
  • 213
  • Possibly, duplicate of http://stackoverflow.com/questions/209686/passing-list-to-sql-stored-procedure – Andrey Agibalov Aug 17 '11 at 17:47
  • What **version** of SQL Server?? 2005?? 2008 ?? 2008 R2 ?? SQL Server 2008 and newer has the concept of "table-valued parameters" (see Redth's response for details) – marc_s Aug 17 '11 at 18:02
  • Unrelated tip: the SqlDataReader is also IDisposable so should be in a `using` block. – Richardissimo Nov 29 '18 at 05:29

8 Answers8

201

If you're using SQL Server 2008, there's a new featured called a User Defined Table Type. Here is an example of how to use it:

Create your User Defined Table Type:

CREATE TYPE [dbo].[StringList] AS TABLE(
    [Item] [NVARCHAR](MAX) NULL
);

Next you need to use it properly in your stored procedure:

CREATE PROCEDURE [dbo].[sp_UseStringList]
    @list StringList READONLY
AS
BEGIN
    -- Just return the items we passed in
    SELECT l.Item FROM @list l;
END

Finally here's some sql to use it in c#:

using (var con = new SqlConnection(connstring))
{
    con.Open();

    using (SqlCommand cmd = new SqlCommand("exec sp_UseStringList @list", con))
    {
        using (var table = new DataTable()) {
          table.Columns.Add("Item", typeof(string));

          for (int i = 0; i < 10; i++)
            table.Rows.Add("Item " + i.ToString());

          var pList = new SqlParameter("@list", SqlDbType.Structured);
          pList.TypeName = "dbo.StringList";
          pList.Value = table;

          cmd.Parameters.Add(pList);

          using (var dr = cmd.ExecuteReader())
          {
            while (dr.Read())
                Console.WriteLine(dr["Item"].ToString());
          }
         }
    }
}

To execute this from SSMS

DECLARE @list AS StringList

INSERT INTO @list VALUES ('Apple')
INSERT INTO @list VALUES ('Banana')
INSERT INTO @list VALUES ('Orange')

-- Alternatively, you can populate @list with an INSERT-SELECT
INSERT INTO @list
   SELECT Name FROM Fruits

EXEC sp_UseStringList @list
Walter Stabosz
  • 7,447
  • 5
  • 43
  • 75
Redth
  • 5,464
  • 6
  • 34
  • 54
  • 10
    Does it have to define a datatable to set the value of the parameter? Any other light approach? – ca9163d9 Dec 13 '12 at 06:56
  • 2
    We tried it but we found its drawback being not supported by Enitiy framework – Bishoy Hanna Aug 12 '14 at 06:12
  • I'm trying to use this with the `IN` clause like so: `SELECT [columnA] FROM [MyTable] WHERE [Id] IN (@List)` but when trying to update my Stored Procedure to do this, SQL Server 2012 tells me that I have to Declare the scalar variable @List. I'm using it in the parameters section like you are so when I try to put DECLARE in front of it I get lots of syntax errors... any ideas @Redth ? – JaKXz Dec 10 '14 at 21:08
  • 8
    **BE CAREFUL WITH THIS SOLUTION IF YOU ARE USIN LINQ2SQL, AS IT DOES NOT SUPPORT USER DEFINED TABLE TYPES AS PARAMETERS!!!** A workaround can be found in Jon Raynor's answer, using comma separated lists and a parser function, however this also has drawbacks.... – Fazi Feb 10 '15 at 15:57
  • 4
    @Fazi in this case, don't use Linq2SQL. It's preferable to string concatenation and parsing in T-SQL – Panagiotis Kanavos Feb 16 '15 at 12:14
  • 2
    Yeah, so how do you actually execute this from SSMS? – Sinaesthetic Apr 04 '17 at 23:35
  • @ca9163d9 Does it accept list<> of strings instead of DataTable? – RollRoll Dec 15 '17 at 15:09
  • @Sinaesthetic I edited the answer to add a example of how to execute from SSMS – Walter Stabosz Nov 29 '18 at 04:49
  • **Heads up**, does not work with linked server connections. http://www.sommarskog.se/arrays-in-sql-2008.html#CLR – Lamar Aug 31 '20 at 22:18
25

The typical pattern in this situation is to pass the elements in a comma delimited list, and then in SQL split that out into a table you can use. Most people usually create a specified function for doing this like:

 INSERT INTO <SomeTempTable>
 SELECT item FROM dbo.SplitCommaString(@myParameter)

And then you can use it in other queries.

Tejs
  • 40,736
  • 10
  • 68
  • 86
15

No, arrays/lists can't be passed to SQL Server directly.

The following options are available:

  1. Passing a comma-delimited list and then having a function in SQL split the list. The comma delimited list will most likely be passed as an Nvarchar()
  2. Pass xml and have a function in SQL Server parse the XML for each value in the list
  3. Use the new defined User Defined table type (SQL 2008)
  4. Dynamically build the SQL and pass in the raw list as "1,2,3,4" and build the SQL statement. This is prone to SQL injection attacks, but it will work.
Jon Raynor
  • 3,804
  • 6
  • 29
  • 43
  • 2
    This is a good summary of the possible options. The third option is the best option in my opinion and do not use the 4th option ever for this purpose. – Kara Kartal Jan 31 '22 at 18:16
  • Passing XML in to a stored procedure can suffer from a problem called parameter sniffing. https://www.red-gate.com/simple-talk/databases/sql-server/t-sql-programming-sql-server/parameter-sniffing/ Best option as #3, as was noted in the best answer, above. Option #4 is valid, but will suffer performance problems as that list gets long (>1000). See STRING_SPLIT() in MS SQL Server 2017+. – Michael Nov 07 '22 at 16:27
2

Yep, make Stored proc parameter as VARCHAR(...) And then pass comma separated values to a stored procedure.

If you are using Sql Server 2008 you can leverage TVP (Table Value Parameters): SQL 2008 TVP and LINQ if structure of QueryTable more complex than array of strings otherwise it would be an overkill because requires table type to be created within SQl Server

sll
  • 61,540
  • 22
  • 104
  • 156
2

Make a datatable with one column instead of List and add strings to the table. You can pass this datatable as structured type and perform another join with title field of your table.

hungryMind
  • 6,931
  • 4
  • 29
  • 45
  • that's the way to go. I actually created a table on the db side and loaded with bcp write to server. – dier Aug 06 '18 at 12:30
1

If you prefer splitting a CSV list in SQL, there's a different way to do it using Common Table Expressions (CTEs). See Efficient way to string split using CTE.

Community
  • 1
  • 1
Larry Silverman
  • 1,043
  • 1
  • 11
  • 30
0
CREATE TYPE [dbo].[StringList1] AS TABLE(
[Item] [NVARCHAR](MAX) NULL,
[counts][nvarchar](20) NULL);

create a TYPE as table and name it as"StringList1"

create PROCEDURE [dbo].[sp_UseStringList1]
@list StringList1 READONLY
AS
BEGIN
    -- Just return the items we passed in
    SELECT l.item,l.counts FROM @list l;
    SELECT l.item,l.counts into tempTable FROM @list l;
 End

The create a procedure as above and name it as "UserStringList1" s

String strConnection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString.ToString();
            SqlConnection con = new SqlConnection(strConnection);
            con.Open();
            var table = new DataTable();

            table.Columns.Add("Item", typeof(string));
            table.Columns.Add("count", typeof(string));

            for (int i = 0; i < 10; i++)
            {
                table.Rows.Add(i.ToString(), (i+i).ToString());

            }
                SqlCommand cmd = new SqlCommand("exec sp_UseStringList1 @list", con);


                    var pList = new SqlParameter("@list", SqlDbType.Structured);
                    pList.TypeName = "dbo.StringList1";
                    pList.Value = table;

                    cmd.Parameters.Add(pList);
                    string result = string.Empty;
                    string counts = string.Empty;
                    var dr = cmd.ExecuteReader();

                    while (dr.Read())
                    {
                        result += dr["Item"].ToString();
                        counts += dr["counts"].ToString();
                    }

in the c#,Try this

Deepalakshmi
  • 81
  • 1
  • 1
0

The only way I'm aware of is building CSV list and then passing it as string. Then, on SP side, just split it and do whatever you need.

Andrey Agibalov
  • 7,624
  • 8
  • 66
  • 111