December 28, 2018 at 3:16 pm
i have 2 FILES (.CSV).
I am just dump loading the raw contents of each into Table1 and Table2 staging table..
THen i need to insert ONLY NEW DATA into the TABLE_TARGET
(same structure as staging tables Table1 and Table2).
I need to insert new row if a row or rows with same id and dtOccurrenceDate field value does not exist,
and update the existing rows the TABLE_TARGET where ID and dtOccurrenceDate field value match., from both table1 and table2
How do i even start ?.... (the holidays also caused partial amnesia to me. I could swear I knew how to do it and did it in the past 🙁 )
Please, give me a hint. Also, one server where such sql should run is a 2000.. so no merge statement there 🙁
Likes to play Chess
December 29, 2018 at 2:28 am
VoldemarG - Friday, December 28, 2018 3:16 PMi have 2 FILES (.CSV).
I am just dump loading the raw contents of each into Table1 and Table2 staging table..
THen i need to insert ONLY NEW DATA into the TABLE_TARGET
(same structure as staging tables Table1 and Table2).
I need to insert new row if a row or rows with same id and dtOccurrenceDate field value does not exist,
and update the existing rows the TABLE_TARGET where ID and dtOccurrenceDate field value match., from both table1 and table2How do i even start ?.... (the holidays also caused partial amnesia to me. I could swear I knew how to do it and did it in the past 🙁 )
Please, give me a hint. Also, one server where such sql should run is a 2000.. so no merge statement there 🙁
December 30, 2018 at 11:12 am
I ended up doing it this way, because same scrtipt needs to be run on both 2016 and 2000 SQL Servers:
--create first table
CREATE TABLE #tblTarget (ID INT, DateOfOccurrence DATE)
INSERT INTO #tblTarget VALUES(1, '01/01/2018'), (2, '01/02/2018')
--create second table with with same rows on fly
CREATE TABLE #tblStage (ID INT, DateOfOccurrence DATE)
INSERT INTO #tblStage VALUES(2, '01/04/2018'), (3, '01/05/2018'), (4, '01/06/2018')
;
SELECT * FROM #tblTarget
SELECT * FROM #tblStage
;
BEGIN TRAN
-- update already existing rows first
UPDATE T1
SET T1.DateOfOccurrence = T2.DateOfOccurrence
FROM #tblStage T2
JOIN #tblTarget T1
ON T1.ID = T2.ID
and T1.DateOfOccurrence= T2.DateOfOccurrence
WHERE T1.ID IS NOT NULL
-- insert new rows
INSERT INTO #tblTarget (ID, DateOfOccurrence)
SELECT T2.ID, T2.DateOfOccurrence
FROM #tblStage T2
LEFT JOIN #tblTarget T1
ON T1.ID = T2.ID
and T1.DateOfOccurrence= T2.DateOfOccurrence
WHERE T1.ID IS NULL
COMMIT TRAN
;
SELECT * FROM #tblTarget
;
DROP TABLE #tblStage
DROP TABLE #tblTarget
Likes to play Chess
January 2, 2019 at 6:21 am
The UPDATE will set the DateOfOccurrence to its existing value (ie. have no effect) because the column is also part of the JOIN criteria.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply