使用asp.net在单个命令中插入多行

时间:2013-05-08 05:31:53

标签: asp.net sql-server sqlconnection sqlcommand

我的asp.net表单中有教育资格块,一组qulification将作为行插入表中。所以我想插入这些集合,假设在一次拍摄中有3组限定条件,例如表格中的3个插入行。我不想创建多个插入队列,因为我正在使用存储过程。我听说xml可以完成这项工作,但不确定。

我们将不胜感激。

3 个答案:

答案 0 :(得分: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

<强> Exec的:

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

答案 1 :(得分:1)

如果您使用的是SQL Server 2008,请使用Table-Valued Parameters一次性执行插入操作

创建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();

答案 2 :(得分: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;
    }
}