I’ve got a table with data named energydata
it has just three columns
(webmeterID, DateTime, kWh)
I have a new set of updated data in a table temp_energydata.
The DateTime and the webmeterID stay the same. But the kWh values need updating from temp_energydata table.
How do I write the T-SQL for this the correct way?
Assuming you want an actual SQL Server
MERGEstatement:If you also want to delete records in the target that aren’t in the source:
Because this has become a bit more popular, I feel like I should expand this answer a bit with some caveats to be aware of.
First, there are several blogs which report concurrency issues with the
MERGEstatement in older versions of SQL Server. I do not know if this issue has ever been addressed in later editions. Either way, this can largely be worked around by specifying theHOLDLOCKorSERIALIZABLElock hint:You can also accomplish the same thing with more restrictive transaction isolation levels.
There are several other known issues with
MERGE. (Note that since Microsoft nuked Connect and didn’t link issues in the old system to issues in the new system, these older issues are hard to track down. Thanks, Microsoft!) From what I can tell, most of them are not common problems or can be worked around with the same locking hints as above, but I haven’t tested them.As it is, even though I’ve never had any problems with the
MERGEstatement myself, I always use theWITH (HOLDLOCK)hint now, and I prefer to use the statement only in the most straightforward of cases.