Passing array of ints to T-SQL stored proc via entity framework

前端 未结 3 344
悲&欢浪女
悲&欢浪女 2020-12-18 07:45

I\'ve read many posts and think I understand the concepts, but my small array of ints fails to pass from a C#/EF module to a SQL Server stored proc. Hoping other eyes can s

相关标签:
3条回答
  • 2020-12-18 08:31

    That worked! For the sake of others I'll post the precise code here, which I had to tweak slightly.

    var dataTable = new DataTable();
    dataTable.TableName = "dbo.IntsTTV";
    dataTable.Columns.Add("Id", typeof(int));
    dataTable.Rows.Add(1); // Id of '1' is valid for the Person table
    
    SqlParameter parameter = new SqlParameter("UserIds", SqlDbType.Structured);
    parameter.TypeName = "dbo.IntsTTV";
    parameter.Value = dataTable;
    var res = _db.Database.SqlQuery<string>("EXEC dbo.GetUsers @UserIds", parameter).ToList();
    
    0 讨论(0)
  • 2020-12-18 08:36

    This is how I call stored procedure with table valued parameter. The main difference being that I use a DataTable parameter.

    I remember having issues with parameter name bindings, but I don't remeber exactly what they were. This explains the change I made in the syntax of the procedure call. I know this one should be working.

    var dataTable = new DataTable();
    dataTable.TableName = "dbo.IntsTTV";
    dataTable.Columns.Add("Id", typeof(int));
    dataTable.Rows.Add(1); // Id of '1' is valid for the Person table
    
    SqlParameter parameter = new SqlParameter("UserIds", SqlDbType.Structured);
    parameter.TypeName = dataTable.TableName;
    parameter.Value = dataTable;
    
    var res = _db.Database.SqlQuery<string>("EXEC GetUsers @UserIds", parameter).ToList();
    
    0 讨论(0)
  • 2020-12-18 08:36

    I know this has been answered by found a different way that might help someone else out there

    STRING_SPLIT

    declare @intArray nvarchar(1000)
    set @intArray = '1,2,3,4,5'
    select value from STRING_SPLIT(@intArray , ',')
    

    This will return a new table with the numbers in your @intArray

    Then you just need to use it as a normal table

    select * from myMainTable where Id in (select value from STRING_SPLIT(@intArray , ','))
    
    0 讨论(0)
提交回复
热议问题