简体   繁体   中英

Find recently added rows and add values

I have a table which is reloaded and trunkated every morning. It doesn't have any date/time-column nor a auto-incremental column.

I need a query which figures out what rows were added each morning and add a new column to the table for each row with a certain value (one if it's new and another one if it's not). Also, if it's possible, add a second column containing the date when the row was added.

What I'm thinking is that I copy the table every day and then compare it with the new the next day.

Is this even possible to do, if so, how can I do it? Is there a better way without changing how the data is written to the table?

Yes, creating the second table seems like a reasonable solution, given the constraints on the original table

Okay, so on day 1, you create your shadow table and populate it:

CREATE TABLE Shadow (/* Same columns as original, plus added date, magic value column */)
INSERT INTO Shadow (/* Same columns as original, plus added date, magic value column */)
SELECT /* Columns, plus todays date and the magic value column */ FROM Original

Then, on subsequent days:

ALTER TABLE Original ADD MagicColumn int null
GO
ALTER TABLE Original ADD AddedDate date null
GO
MERGE INTO Original o
USING Shadow s
     ON o.PK1 = s.PK1 and o.PK2 = s.PK2

WHEN MATCHED
   THEN UPDATE
      SET
         AddedDate = s.AddedDate,
         MagicColumn = 1 /* Value for updated */

WHEN NOT MATCHED BY SOURCE
   THEN UPDATE
      SET
         AddedDate = CURRENT_TIMESTAMP,
         MagicColumn = 0; /* Value for new */
GO
TRUNCATE TABLE Shadow
GO
INSERT INTO Shadow (/* Same columns as original, plus added date, magic value column */)
SELECT /* All columns */ FROM Original

Some of these statements need to be in separate batches (eg the ALTER TABLE ones need to be in a different batch than the MERGE ), so if you're doing this in an SQL Agent job, they ought to be in separate steps.

I keep referring to the "magic value column", because I'm not sure what to call the column that contains:

a certain value (one if it's new and another one if it's not)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM