How to pass table value parameters to stored procedure from .net code

后端 未结 5 2228
难免孤独
难免孤独 2020-11-22 00:35

I have a SQL Server 2005 database. In a few procedures I have table parameters that I pass to a stored proc as an nvarchar (separated by commas) and internally

5条回答
  •  故里飘歌
    2020-11-22 01:04

    Further to Ryan's answer you will also need to set the DataColumn's Ordinal property if you are dealing with a table-valued parameter with multiple columns whose ordinals are not in alphabetical order.

    As an example, if you have the following table value that is used as a parameter in SQL:

    CREATE TYPE NodeFilter AS TABLE (
      ID int not null
      Code nvarchar(10) not null,
    );
    

    You would need to order your columns as such in C#:

    table.Columns["ID"].SetOrdinal(0);
    // this also bumps Code to ordinal of 1
    // if you have more than 2 cols then you would need to set more ordinals
    

    If you fail to do this you will get a parse error, failed to convert nvarchar to int.

提交回复
热议问题