Create a user defined table type in c# to use in sql server stored procedure

浪尽此生 提交于 2020-01-19 11:37:50

问题


I'm trying to write a c# program which creates a whole table to send back to a sql server stored procedure.

I came across the msdn guide but became incredibly confused: http://msdn.microsoft.com/en-us/library/cc879253.aspx

I tried to use the msdn guide but get an error despite adding references to microsoft.sqlserver.smo, microsoft.sqlserver.connectioninfo, microsoft.sqlserver.management.sdk.sfc as suggested by the compiler. The error is: "Set parent failed for userdefinedtabletype". (code snippet based on msdn guide)

Server srv = new Server();
Database db = srv.Databases["MyDatabase"];

//fails at this line
UserDefinedTableType udtt = new UserDefinedTableType(db, "TestTable");
udtt.Columns.Add(new Column(udtt, "Col1", DataType.Int));
udtt.Create();

I would simply like to be able to build a user defined data table, the only related questions I've found here deal only with creating a user defined table in SQL, not C#.

My SQL Server connection code is this:

 DataSet ds = new DataSet("SQLDatabase");

       using (SqlConnection conn = new SqlConnection(Settings.Default.SQLConnectionString))
       {
           SqlCommand sqlComm = new SqlCommand("StoredProcedure", conn);

           sqlComm.Parameters.AddWithValue("@param", paramValue);

           sqlComm.CommandType = CommandType.StoredProcedure;

           SqlDataAdapter da = new SqlDataAdapter();
           da.SelectCommand = sqlComm;
           da.Fill(ds);
       }

Please could someone show me in simple language, how to create a user defined table type in my C# program?

Hope I've been clear enough, Thanks in advance.


回答1:


Simplest option is to create a DataTable in C# code and pass it as a parameter to your procedure. Assuming that you have created a User Defined Table Type as:

CREATE TYPE [dbo].[userdefinedtabletype] AS TABLE(
    [ID] [varchar](255) NULL,
    [Name] [varchar](255) NULL
)

then in your C# code you would do:

DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof (string));
dt.Columns.Add("Name", typeof (string));
//populate your Datatable

SqlParameter param = new SqlParameter("@userdefinedtabletypeparameter", SqlDbType.Structured)
{
    TypeName = "dbo.userdefinedtabletype",
    Value = dt
};
sqlComm.Parameters.Add(param);

Remember to specify SqlDbType.Structured as the type of parameter and specify the name you have used in creating your UDT.



来源:https://stackoverflow.com/questions/25870904/create-a-user-defined-table-type-in-c-sharp-to-use-in-sql-server-stored-procedur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!