I was wondering if there was a way that I can do the folloing in one sql statement.
I am parsing an csv file for product ins开发者_运维百科ertion into the database. is there a way that I can check to see if an entry in a table with X equaling to N, if so update the rest f the columns else insert it?
regards
Phil
This type of operation is sometimes called an "UPSERT". The SQL standard way to do it is to use the MERGE
statement, but unfortunately it is not widely implemented yet.
Some databases have added their own ways to do it, such as the non-standard MySQL extensions REPLACE
and INSERT ... ON DUPLICATE KEY UPDATE
.
The MERGE statement will get you there, but it's only available on SQL Server 2008 R2. You would otherwise need to treat this as a Slowly Changing Dimension and either bring the data into a temp table and compare or use an integration services package to do the work.
Would something like this work for you?
if(update myTable where x='n')
else{
insert into myTable(x,y,z) values(1,2,3)
}
The update query will run regardless, and will return false if it couldn't update that record, causing it to do the insert.
精彩评论