【问题标题】:sqlbulkcopy insert into sql server [duplicate]sqlbulkcopy 插入到 sql server [重复]
【发布时间】:2014-05-13 09:26:56
【问题描述】:

在我的 sqlserver 表中,我定义了以下列, stationid,dateofevent,itemname,sitename,clicks

To populate above table , we have a c# application. In which inserts data in a loop. Data comes from remote machine and once data received by server(another c# application) , it imserts into sql server and send back OK response to remote client. When client receives response , it archives data into another table and deletes the data from actual table.

Incase if client fails to archive , stored procedure from server side will take care of preventing duplicate record insert.

    Set @previousClickCount=( SELECT Clicks FROM [Analytics] as pc
                                 where DATEADD(dd, 0, DATEDIFF(dd, 0, [DateOfEvent]))=@date
                                 and ItemType=@type
                                 and stationId = @stationId 
                                 and ItemName=@itemName 
                                 and SiteName=@siteName)
    If @previousClickCount Is Null
        Begin
        -- Row for this item is not found in DB so inserting a new row
            Insert into Analytics(StationId,DateOfEvent,WeekOfYear,MonthOfYear,Year,ItemType,ItemName,Clicks,SiteName)
            VALUES(@stationId,@date,DATEPART(wk,@date),DATEPART(mm,@date),DATEPART(YYYY,@date),@type,@itemName,@clicks,@siteName)
        End

Later we decided to move to bulk insert in server side code. So that we can avoid looping.             

bulkCopy.DestinationTableName = SqlTableName;
bulkCopy.BatchSize = 1000;
bulkCopy.BulkCopyTimeout = 1000;
bulkCopy.WriteToServer(dataTable);

But incase client side failed to archive data then server will insert duplicate record.Is there any way to check this in bulk insert or whether can we add any constraint like,insert only if the itemname not present for the particular date then insert.

问候 桑吉萨

【问题讨论】:

  • bulkcopy 就是这样做的——直接复制。没有验证,什么都没有。您可以在表上添加触发器,以便当复制完成或批处理完成并提交时,触发器将触发,但任何异常无疑都不会提交批处理。

标签: c# sql-server-2008 bulkinsert


【解决方案1】:

绝对有一种方法可以在 SqlBulkCopy 中进行检查 - 不进行检查。

不要插入到最终表中(无论如何这更好,SqlBulkCopy 对其锁定有严重的错误编程),而是插入到一个临时表中(您可以动态创建)。

然后您可以执行自定义 SQL 以将数据移动到最终表中,例如使用避免重复的 MERGE 语句。这不仅会为您提供更好的多客户端行为(因为您可以避免 SqlBulkCopy 在 rel dat 表上的非常糟糕的锁定行为),而且还允许上传的数据发生各种 ETL 事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多