11
How can I condition the insertion of a record in a table in SQL Server using the T-SQL language considering the following rules:
- If the record to be inserted already exists in the table, only update the field referring to the record modification date;
- If the record does not yet exist, enter the same assignment to the current date in the field referring to the record modification date.
For example, given the table DatasBase
with the following structure:
+--------------------------------------+
| DatesBase |
+--------------------------------------+
| PK DateBase DATETIME NOT NULL |
| DateAtualizacao DATETIME NOT NULL |
+--------------------------------------+
where, I have a record of dates used in another table with their respective update dates. We assume that we need to enter the date '2013-12-12'
in this table, however, if it already exists in the table, I only need to update the field DateAtualizacao
.
Correct me if I was wrong, but I think this is the best solution because for the bank is just an operation.
– talles
I think that in the case of "upsert" of a line this solution should be equivalent to Luiz Ricardo’s (I did not understand the rejection of his answer). In the case of a batch upsert, my solution should be faster as it basically works like a Join, not requiring EXISTS for each line.
– bfavaretto
There are those think that MERGE is a little better for the reason that @Talles mentioned. Note that MERGE is available as of 2008 version of SQL Server, my solution does not have this limitation, but unfortunately the author of the question did not specify anything in this regard.
– utluiz
This method is not compatible with all SQL versions although it is right.
– Marcelo de Aguiar
@Marcelodeaguiar I edited to make this clear.
– bfavaretto