-
Notifications
You must be signed in to change notification settings - Fork 50
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement Upsert with single SQL statement #34
Comments
Thanks for your input, I'll take it into account |
MySQL 5 also supports an "upsert" syntax as documented here:
This blog post provides a great example of using it:
Some key takeaways from the docs:
|
Cool, thank you! |
Be careful with MERGE on MS SQL without transaction. |
Dear developer,
The current incarnation (2.3) of SqlFu has Upsert method in CrudHelpers.cs. The upsert (ie. UpdateOrInsert) is a great facility and used in real world applications. I like it!
The implementation seems to try to update the record first and then insert it if the update fails. This two-pass protocol is "chatty". The single statement upsert would be far more efficient due to reduced round-trips to the database.
There are two ways of implementing single statement upsert. The traditional method is a combination of both UPDATE and INSERT statements. The fast method takes advantage of MERGE statement and VALUES table constructor.
A demostration of upsert without autogenerated primary key.
A demostration of upsert when primary key value is generated by database. Please note the presence of OUTPUT clause. It allows the library the read back any value generated by the database.
I prefer MERGE statement over combining IF EXISTS, UPDATE and INSERT. MERGE statement is easier to query optimizer and does its job in single pass. The added benefit of MERGE statement is atomicity. I do not need to wrap the call of upsert method inside transaction!
For more information about the implementation of the MERGE statement in Microsoft SQL Server, please visit http://msdn.microsoft.com/en-us/library/bb510625(v=sql.100).aspx.
MERGE statatement has been supported since SQL Server 2008.
I hope this helps you to develop the best micro-orm available to the community of the .NET developers!
Keep going!
Kind regards,
Olli-Pekka Isola
The text was updated successfully, but these errors were encountered: