假设我必须将具有5列的datatable
保存到具有6列的用户定义的表类型变量。第一列是自动增量从1开始增加1
这是它的结构:
create type dbo.SelectedCourses
as table
(
CntrNo int not null IDENTITY(1, 1),
CRSID int,
YearNo int,
IsCompulsory varchar(20),
EntDT datetime,
EmpID int
);
go
在stored procedure
中声明为:
create proc USPSvUpdtACDProgramFromTypes
-- has global variables above
@pSelCRSInfo as dbo.SelectedCourses READONLY
-- has global variables here
as
begin
-- code here
end
我的问题是如何在5个列的客户端中构造datatable
并将其添加到包含6列的UDTT变量(首先是auto increment
)。如果我在不考虑列计数的情况下分配它,datatable
的第一列将映射到自动增量列,SQL将引发错误。
感谢
答案 0 :(得分:3)
您可以使用SqlMetaData
以下是UDTT的完整示例:
CREATE TYPE [dbo].[test_table] AS TABLE(
ID int identity (1,1) NOT NULL,
Name varchar(50) NOT NULL
)
使用SqlMetaData
var sqlMetaData = new[]
{
new SqlMetaData("ID", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("Name", SqlDbType.NVarChar, 50)
};
var sqlRecords = new HashSet<SqlDataRecord>();
var sqlRec = new SqlDataRecord(sqlMetaData);
sqlRec.SetString(1, "Nyan");
sqlRecords.Add(sqlRec);
var conn = new SqlConnection("connstring");
try
{
conn.Open();
using (var cmd = new SqlCommand("tests", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
var param = new SqlParameter("@tbl", SqlDbType.Structured) { Value = sqlRecords };
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Console.WriteLine("Error in tests.");
Console.WriteLine(ex.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}