I am writing a stored procedure to regularly copy data from multiple source tables to a destination table. I would like to insert data from one column of a source table into the destination table, and then update the destination table based on that column.
I have written a stored procedure that:
- Inserts into the destination table datetime data from a source table, checking to not insert any datetime values that already exist at the destination.
- Updates the rest of the destination columns based on the source columns, going back in time far enough that any changes to previous data should be captured.
BEGIN TRANSACTION;
BEGIN TRY
INSERT INTO DestTbl (DtTm)
SELECT
TblA.DtTm
FROM
TblA
WHERE
TblA.DtTm > DATEADD(DAY, -1, GETDATE())
AND TblA.DtTm NOT IN
(
SELECT
DestTbl.DtTm
FROM
DestTbl
)
ORDER BY
TblA.DtTm ASC;
COMMIT TRANSACTION;
END TRY
-- There is a transaction like this for each source table
BEGIN TRANSACTION;
BEGIN TRY
UPDATE
DestTbl
SET
DestTbl.Col2 = TblB.SomeCol
FROM
DestTbl
INNER JOIN
TblB
ON
TblB.DtTm > DATEADD(DAY, -1, GETDATE())
AND DestTbl.DtTm = TblB.DtTm;
COMMIT TRANSACTION;
END TRY
What is the best way to ensure that my INSERT is performed before the UPDATE statement? Or should I just refactor my queries to be like this: https://stackoverflow.com/a/11010548?
Thank you.