How to automatically truncate string when do bulk insert?

后端 未结 3 1425
故里飘歌
故里飘歌 2021-02-13 21:13

I want to insert many rows (constructed from Entity Framework objects) to SQL Server. The problem is, some of string properties have length exceeded length of column in database

相关标签:
3条回答
  • 2021-02-13 21:44

    Always use a staging/load table for bulk actions.

    Then you can process, clean, scrub etc the data before flushing to the real table. This includes, LEFTs, lookups, de-duplications etc

    So:

    1. Load a staging table with wide columns
    2. Flush from staging to "real" table using INSERT realtable (..) SELECT LEFT(..), .. FROM Staging
    0 讨论(0)
  • 2021-02-13 21:45

    Try Using SQLTransaction Class while using SQLBulkCopy Class

    0 讨论(0)
  • 2021-02-13 21:46

    Unfortunately there is no direct way of doing that with SqlBulkCopy. SQL Bulk Inserts are by nature almost "dumb" but that's why they are so fast. They aren't even logged (except capturing SqlRowsCopied event) so if something fails, there's not much information. What you're looking for would in a way, be counter to the purpose of this class

    But there can be 2 possible ways:

    • You can try using SqlBulkCopyOptionsEnumeration (passed to SqlBulkCopy() Constructor) and use SqlBulkCopyOptions.CheckConstraints (Check constraints while data is being inserted. By default, constraints are not checked.).

    • Or you can use SqlBulkCopyOptions.FireTriggers Enumeration (When specified, cause the server to fire the insert triggers for the rows being inserted into the database.) and handle the exception in SQL Server Insert Trigger.

    0 讨论(0)
提交回复
热议问题