0

我的 asp.net 表单中有教育资格块,一组资格将作为行插入表中。所以我想插入这些集合,假设一次有 3 组资格,比如在表中的一个镜头中插入 3 行。我不想在使用存储过程时创建多个插入查询。我听说 xml 可以完成这项工作,但不确定。

您的帮助将不胜感激。

4

3 回答 3

2

您可以从客户端生成 XML 并将其发送到 SP -

SP:

CREATE PROCEDURE dbo.sp_test

    @XML XML

AS BEGIN

    SET NOCOUNT ON

    --INSERT INTO dbo.ScheduleDetail (ScheduleID, DateOut, WorkShiftCD, AbsenceCode)
    SELECT 
          ScheduleID = t.p.value('@ScheduleID', 'INT') 
        , DateOut = t.p.value('@DateOut', 'DATETIME') 
        , WorkShiftCD = t.p.value('@WorkShiftCD', 'VARCHAR(50)') 
        , AbsenceCode = t.p.value('@AbsenceCode', 'VARCHAR(50)') 
    FROM @XML.nodes('root/sd') t(p)

    RETURN 0

END

执行:

DECLARE @XML XML
SELECT @XML = '
<root>
  <sd ScheduleID="11324" DateOut="2009-01-01T00:00:00" AbsenceCode="offdays" />
  <sd ScheduleID="11324" DateOut="2009-01-02T00:00:00" WorkShiftCD="1/10" />
  <sd ScheduleID="11324" DateOut="2009-01-03T00:00:00" WorkShiftCD="1/11,5" />
  <sd ScheduleID="11324" DateOut="2009-01-04T00:00:00" WorkShiftCD="1/7" />
  <sd ScheduleID="11324" DateOut="2009-01-05T00:00:00" AbsenceCode="business_trip" />
  <sd ScheduleID="11324" DateOut="2009-01-06T00:00:00" AbsenceCode="offdays" />
</root>'

EXEC dbo.sp_test @XML = @XML
于 2013-05-08T05:54:17.090 回答
1

如果您使用的是 SQL Server 2008,则使用表值参数一次性执行插入操作

创造TVP

CREATE TYPE tvp_Insert AS TABLE
    (
     [ID] [int] NOT NULL,
     [Name] [nvarchar](50) NULL
    )

创建一个将值从 TVP 插入到目标表的过程

CREATE PROCEDURE usp_tvp_Insert  @ItemTVP tvp_Insert READONLY
AS
BEGIN
INSERT INTO YourTable (ID, Name)
SELECT ID, Name
FROM @ItemTVP
END

C# 代码

 SqlCommand sqlCmd = new SqlCommand("usp_tvp_Insert", con);
 sqlCmd.CommandType = CommandType.StoredProcedure;
 SqlParameter tvpParam = sqlCmd.Parameters.AddWithValue("@ItemTVP", datatable);
 //Pass the datatable above 
 tvpParam.SqlDbType = SqlDbType.Structured; //passing TVP
 sqlCmd.ExecuteNonQuery();
于 2013-05-08T05:58:04.390 回答
0

您可以按照以下代码在代码中使用 SqlBulkCopy

public void InsertDataTable(DataTable dt)
{
    try
    {

        if (dt.Rows.Count > 0)
        {
            SqlBulkCopy bulk = new SqlBulkCopy(ConnectionString);
            bulk.DestinationTableName = "YourTableName";
            bulk.WriteToServer(dt);
        }

    }
    catch (Exception)
    {
        throw;
    }
}
于 2013-05-08T07:37:00.247 回答