Click here to Skip to main content
15,890,995 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I use SQL Server 2012 and Entity Framework6.

I created table valued parameter:
SQL
CREATE TYPE IdArray AS TABLE 
    (
         Id int
    );

And here my stored procedure:

SQL
ALTER PROCEDURE [dbo].[SP_TEST_TLP]
        @List dbo.IdArray READONLY 
    AS 
    BEGIN
        SET NOCOUNT ON;
    
        SELECT * 
        FROM Clients 
        WHERE Clients.Id IN ( '@List' )
    END


From Visual Studio I call stored procedure and passing paramaters to stored procedure.

I do it this way:

Create DataTable:

C#
var myDataTable = new DataTable();
     myDataTable.Columns.Add("Id", typeof(int));

     myDataTable.Rows.Add(1);
     myDataTable.Rows.Add(3);
     myDataTable.Rows.Add(6);


Creating `SqlParameter` from DataTable:
C#
SqlParameter parameter = new SqlParameter();
     parameter.ParameterName = "@List";
     parameter.SqlDbType = System.Data.SqlDbType.Structured;
     parameter.TypeName = "dbo.IdArray";
     parameter.Value = myDataTable;


Fire stored procedure and passing parameter:
C#
var data = _context.Database.ExecuteSqlCommand("SP_TEST_TLP @List", parameter);


The problem is that `ExecuteSqlCommand` returns -1.

Why `ExecuteSqlCommand` returns -1 while I expect rows from database?

What I have tried:

I tryed the above but it didn't work!
Posted

1 solution

The in list does not work this way. You cannot pass a list in a single parameter and expect it to return rows.

The proper syntax for IN is
SQL
columnname IN (value1, value2, value3, ...)

In order for IN to work you need to interpret the list in the stored procedure. There are quite a few articles about this, for example:
- Passing comma delimited parameter to stored procedure[^]
- Passing a Comma Delimited Parameter to a Stored Procedure[^]
- Building Dynamic SQL In a Stored Procedure[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900