zzzprojects / Bulk-Operations

C# SQL Bulk Operations | High-performance C# bulk insert, update, delete and merge for SQL Server, SQL Azure, SQL Compact, MySQL, and SQLite.
https://bulk-operations.net
142 stars 36 forks source link

Setting the join indicator in BulkMerge method #68

Open Song-s-z opened 3 years ago

Song-s-z commented 3 years ago

Hi , to avoid the constraint issues, could I set the join indicators for BulkMerge method? just like in the following merge query, I will get some exceptions: e.g. Cannot insert duplicate key row in object 'dbo.table1' with unique index ..

Could I know the default join indicators in BulkMerge? image

JonathanMagnan commented 3 years ago

Hello @Song-s-z ,

Sure that's possible.

By default, the join uses the primary keys in your database or your identity column.

You can customize it by choosing yourselves each column should be used as a primary key: https://bulk-operations.net/bulk-merge#merge-with-custom-key

You can also add more conditions using MergePrimaryKeyAndFormula which append the SQL to this section.

Let me know if that answers correctly to your question or your need more help.

Best Regards,

Jon

Song-s-z commented 3 years ago

Hi Jon,

I can't believe you could response me so quickly. Thanks very much!

Is it correct that customizing each column like following?

bulk.AutoMapKeyName = "column1";
bulk.AutoMapKeyName = "column2";
bulk.AutoMapKeyName = "column3";
bulk.BulkMerge(customers);

btw, is there a document about MergePrimaryKeyAndFormula ?

Thanks! Karl

JonathanMagnan commented 3 years ago

Hello @Song-s-z ,

No that's bad as you will keep overriding the old property values.

However, you can use the semicolons to specify more than one keys:

bulk.AutoMapKeyName = "column1;column2;column3";

Unfortunately, not documentation is still incomplete. So documentation on some options such as MergePrimaryKeyAndFormula is missing.

Essentially, it appends the current SQL to the key on the ON part. You must use DestinationTableName or StagingTableName as your alias depending on what you want to do. The best way to check what's executed and fix error syntax is by using SQL Profiler to see how to code has been generated.

Song-s-z commented 3 years ago

It's very helpful to me, thanks very much!!!

JonathanMagnan commented 3 years ago

Hello @Song-s-z ,

Glad we could help!

Don't hesitate to contact us with any questions or further assistance!

Best regards,

Jon