Adapter.update(Datatable)的适当配置是什么?

时间:2015-06-05 02:40:51

标签: c# asp.net sql-server dataadapter sqldataadapter

我有一个存储过程,插入一些记录然后更新它

CREATE PROCEDURE [dbo].[InsertSponsors]
@Someparameters  nvarchar(100),
@Anotherparameter int,
AS

Begin

DECLARE @ID int,

 @RowCount int

    insert into Clients (Name,Photo,PolicyID,BirthDay,
    Gender,Title,Nationality,Relationship,ClassID,HRID,Active,
    StartingDate,EndingDate,AddingDate,CreationOwner,UniqueID,PassportNo)
    values (@Name,@Photo,@PolicyID,@Birthday,@Gendar,@Title,@Nationality,@RelationShip,
    @ClassID,@HRID,@Active,@StartingDate,@EndingDate,@AddingDate,@CreationOwner,@UniqueID,@PassportNo)

    SELECT @RowCount = @@ROWCOUNT;

    Select @ID=SCOPE_IDENTITY();
    update Clients set SponsorID=@ID where ID=@ID;


End

我从DataAdapter调用此存储过程,如下所示

注意:我已经尝试了所有已评论的代码,但没有运气

internal static int UpdateInsertAdapter(string query,DataTable dt, SqlParameter[] sqlParameters, bool SP)
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = openConnection();
            cmd.CommandText = query;
            if (SP)
            {
                cmd.CommandType = CommandType.StoredProcedure;
            }
            cmd.UpdatedRowSource = UpdateRowSource.None;
            foreach (SqlParameter parameter in sqlParameters)
            {
                cmd.Parameters.Add(parameter);
            }

            SqlDataAdapter adpt = new SqlDataAdapter();
            //adpt.AcceptChangesDuringFill = true;
            //adpt.AcceptChangesDuringUpdate = true;  
            //SqlCommandBuilder cmdb = new SqlCommandBuilder(adpt);
            //adpt.InsertCommand = cmdb.GetInsertCommand();
            adpt.InsertCommand = cmd;

            **//////Should i've select command to select the @RowCount**

            adpt.UpdateBatchSize = 10;

            int recordsInserted = adpt.Update(dt);
            return recordsInserted;
        }

注意:

我使用ExcelDataReader读取此数据表,然后我将两个DataColumns添加到该数据表

问题

如何批量插入Datatable并选择插入的行。

在本文Codeproject Multiple Ways to do Multiple Inserts中,作者写了一个存储过程只是为了插入可以插入然后更新

错误:

  

1.Update在传递带有修改行的DataRow集合时需要有效的UpdateCommand

     

2.需要初始化DataAdapter.SelectCommand属性。

更新

根据jmcilhinney帮助,我找出了错误#1的原因,并且我已经通过用户question使用SqlCommandBuilder在此Dan找到了解决方案。

            SqlCommandBuilder cmdb = new SqlCommandBuilder(adpt);
            adpt.InsertCommand = cmd;
            adpt.UpdateCommand = new SqlCommandBuilder(adpt).GetUpdateCommand();

但是当我使用这些行时会发生错误#2。

0 个答案:

没有答案