0

I'm using a stored procedure - how can I pass a string like:

'White','Black','Green'

I'm trying to execute a procedure as follows:

 var data = new List<dynamic>();
 string colorstr = "'White','Black','Green'";
 using (SqlConnection connection = new SqlConnection(connectionString))
 {
     connection.Open();
     string sql = $"exec GetData '{colorstr }'";
     data = connection.Query(sql).AsList();
     connection.Close();
 }

This gives an error:

incorrect syntax near 'White'

So the question is how can I pass a comma separated string with single quotes to a stored procedure?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Faisal
  • 584
  • 3
  • 11
  • 33
  • 1
    Possible duplicate of [How do I escape a single quote in SQL Server?](https://stackoverflow.com/questions/1586560/how-do-i-escape-a-single-quote-in-sql-server) – Joakim Danielson Apr 26 '19 at 07:11
  • i don't want escape i need to add – Faisal Apr 26 '19 at 07:13
  • You'd better use parameterization in your queries and won't concern about quotes anymore. – Denis Rubashkin Apr 26 '19 at 07:17
  • @Faisal google [`Table-Valued Parameters`](https://learn.microsoft.com/en-us/sql/relational-databases/tables/use-table-valued-parameters-database-engine?view=sql-server-2017) , instead of passing a comma delimited list pass a table to your stored procedure. It will be a much cleaner solution with some performance benefits too. – M.Ali Apr 26 '19 at 07:19

2 Answers2

3

You are creating a SQL Injection problem. Instead, use SQL Command like below. You avoid the problem and SQL injection


    using (SqlCommand cmd = new SqlCommand("connectionString", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.Add("@colorstr", SqlDbType.VarChar).Value = "'White','Black','Green'";

      con.Open();
      cmd.ExecuteNonQuery();
    }

I don't know your parameter name so I used colorstr, and parameter type, so I used SqlDbType.VarChar. Check it in DB and fix.

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
0

You're actually looking for how pass an array as a parameter to a stored procedure. SQL Server doesnt explicity support arrays as a parameter but there are ways to get it to work using XML or using the List variable type.

For more information see: How to pass an array into a SQL Server stored procedure

TheLegendaryCopyCoder
  • 1,658
  • 3
  • 25
  • 46