I'm trying to get a working solution for a arguably pretty simple task:
I have a simple query like this:
INSERT INTO [INTRANET].[dbo].[SOME_STATUS]
([AUS_STATUS_VID]
,[AUS_STATUS_STATUS]
,[AUS_STATUS_JAHR]
,[AUS_STAUTS_END]
)
SELECT DISTINCT CD_CLVID, '1', '2017', '0'
FROM [SNTRANET].[dbo].[SOME_DETAILS]
WHERE CD_JAHR = 2017
Long story short: Filling up a table with results from another table. Now it seems like, that I have inconsistent data given to me. I was trying to find a solution similar to replace into
or on duplicate key update
(which I was used to from MySQL). However, T-SQL doesn't seem to have this.
Is there an easy solution which just skips the dupe key and continues with the rest of the resultset?
I'm using SQLServer 2008 R2
Edit 1
As requested, the error-message:
Violation of PRIMARY KEY constraint 'PK_T_KB_AUSZAHLUNG_STATUS'. Cannot insert duplicate key in object 'dbo.T_KB_AUSZAHLUNG_STATUS'. The duplicate key value is (7463).
4条答案
按热度按时间y0u0uwnf1#
if the duplicate key is the
[AUS_STATUS_VID]
column then try using Alias on the tables and NOT EXISTShts6caw32#
use the ROW_NUMBER() to ensure you incoming result does not have duplicate and then the
WHERE
clause to ensure it does not exists in the destination tablejyztefdp3#
You can use the SQL Server Merge Statement feature. It will Insert a New Row if no match was found or Else Update the existing records for the Matches:
Example :
Here if a match is found in table BookInventory for a BookOrder .TitleId then the record get inserted and otherwise, the Matched record will Be updates.
You can also achieve the same using multiple statements. Like this
Or in the Direct Insert, Just check the existence to skip the records that are already in the Target table
aemubtdh4#
If CD_CLVID is the PK in [SNTRANET].[dbo].[SOME_DETAILS] then you would not need the distinct