【问题标题】:How do I save a collection to a user defined data type with an auto increment column?如何使用自动增量列将集合保存到用户定义的数据类型?
【发布时间】:2017-10-27 22:20:11
【问题描述】:

假设我必须将包含五列的 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 并将其添加到包含六列的 UDTT 变量中(首先是 auto increment)。如果我在不考虑列计数的情况下分配它,datatable 的第一列将映射到自动递增列,SQL 将抛出错误。

谢谢

【问题讨论】:

  • 首先,您为什么要在客户端中构建一个包含 5 列的数据表而不使用您的 UDT?
  • 我没有在客户端的SQLParameter中使用@pSelCRSInfo

标签: c# sql sql-server-2008 tsql


【解决方案1】:

您可以使用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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2015-05-22
    • 2020-11-08
    相关资源
    最近更新 更多