7

I have no idea where to start or how this will work and I am hoping someone has an idea or a proven method.

To show an example of what I am trying to do, I created a stored procedure which UPDATES or INSERT new records in a Local table by getting records from a link table. The Stored procedure runs as a Job in SQL Server to update and insert new records.

My question is: Is there a way to query the data in the Local Table so That initially I can get all the records but than get only new records that has been inserted or old records that are updated?

I do not want to continuously get all the records, just the new records added or the records updated.

Is this possible?

Here is the stored procedure I ave created as an example to updated the Local Phone data:

CREATE PROCEDURE sp_UPDATE_PHONE_RECORDS
AS 
BEGIN
MERGE dbo.PHONE_REC AS Target
USING (SELECT MEMBER_ID 
      ,HOME_PHONE = dbo.udf_StdPhoneFmt(HOME)
      ,CELL_PHONE = dbo.udf_StdPhoneFmt(CELL)
      ,WORK_PHONE = dbo.udf_StdPhoneFmt(WORK)

FROM PHONE WHERE MEMBER_ID IS NOT NULL) AS SOURCE

ON (Target.MEMBER_ID = SOURCE.MEMBER_ID)

WHEN MATCHED THEN

    UPDATE SET Target.HOME_PHONE = Source.HOME_PHONE,Target.CELL_PHONE = Source.CELL_PHONE,
    Target.WORK_PHONE = Source.WORK_PHONE

WHEN NOT MATCHED BY TARGET THEN
    INSERT (MEMBER_ID, HOME_PHONE, CELL_PHONE ,WORK_PHONE)

    VALUES (Source.MEMBER_ID, Source.HOME_PHONE, Source.CELL_PHONE, Source.WORK_PHONE);
END
GO

Is this possible?

Thanks everyone!

1

5 Answers 5

6

What we typically do is add two date / time fields to the source table, something like Source.LastModifiedOn and Source.CreatedOn.

Then when the job runs to update the target table you can say get me all the Source.LastModifiedOn and Source.CreatedOn rows since the last time the job ran and do your updates / inserts based on the rows.

Of course you will need to be sure the Source.LastModifiedOn and Source.CreatedOn are setup correctly.

1
  • 1
    This is an interesting approach. :) Thanks again! Apr 30, 2012 at 23:59
4

I would use OUTPUT clause with $action column:

DECLARE @Target TABLE
(
    Id INT NOT NULL,
    Value VARCHAR(10) NULL
);
INSERT  @Target
VALUES  (1, 'A'),  (2, NULL), (3, NULL);    
DECLARE @Source TABLE
(
    Id INT NOT NULL,
    Value VARCHAR(10) NULL
);
INSERT  @Source
VALUES  (2, 'B'), (4, 'D'), (5, 'E');
DECLARE @AffectedRows TABLE
(
    MergeAction     NVARCHAR(10) NOT NULL,
    Old_Id          INT NULL,
    Old_Value       VARCHAR(10) NULL,
    New_Id          INT NULL,
    New_Value       VARCHAR(10) NULL
);

MERGE   @Target t
USING   @Source s ON t.Id = s.Id
WHEN MATCHED THEN
        UPDATE SET Value = s.Value
WHEN NOT MATCHED THEN
        INSERT (Id, Value) VALUES (s.Id, s.Value)
OUTPUT  $action, deleted.Id, deleted.Value, inserted.Id, inserted.Value 
        INTO @AffectedRows(MergeAction, Old_Id, Old_Value, New_Id, New_Value);

SELECT  * FROM  @Target;
SELECT  * FROM  @AffectedRows;

Results:

Id Value
-- -----
1  A
2  B    <-- updated row
3  NULL
4  D    <-- inserted row
5  E    <-- inserted row

MergeAction Old_Id      Old_Value  New_Id      New_Value
----------- ----------- ---------- ----------- ---------
INSERT      NULL        NULL       4           D
INSERT      NULL        NULL       5           E
UPDATE      2           NULL       2           B
2
  • 1
    I am going to work with your example and return with feedback, don't want to mark it as answer, just in case I have other questions. But thanks for taking your time to answer. :) Apr 30, 2012 at 23:58
  • @UnaverageGuy: If you have questions, then feel free to ask. If I know the answer, then I will help you. May 1, 2012 at 8:40
0

You can write a Trigger on your local table which will fire when an update or insert is done on it. As a part of trigger logic you have to insert those updated or newly inserted records in to a temporary table. This is the simplest way where you can keep record of your changes to local table.

0

This is basically a variation of RDotLee's answer, but it's an alternative approach that I use sometimes when I don't care about the actual date/time when the records were created:

I just add one bit field called modified with default value 1.
If a new row is inserted into the table, modified is set to 1 automatically.
If an existing row is updated, I have to make sure that modified is set to 1 as well.

That way, the job only needs to search for all rows with modified = 1.
No need to keep track of the date/time when the job was last executed.

When the job was executed successfully, the last thing it does is "resetting" the modified field in all rows:

update TheTable set modified = 0

IMO, this approach is less work when you just care about that the rows were modified since the last job run, but not when they were modified.

But it has the same disadvantage as RDotLee's "LastModifiedOn/CreatedOn" approach - you need to make sure that each and every update on the table really sets the modified column to 1, so you can only use this when you are in control of all code that writes to the table.

5
  • Okay, I found a solution that works, not sure it's the best, it's a combination of the ideas posted here. What I did was create a TIME_STAMP column on the LOCAL Table. This adds a SMALLDATETIME to the records(row) every time a record is updated or when new records are inserted. Now I can query the Local table base on Record updated or inserted in the last 24 hours or between this time and that time using the TIME_STAMP. How can I post the coded back here? May 1, 2012 at 18:47
  • @UnaverageGuy Do you mean TimeStamp? That is not a SmallDateTime. And I posted it as an answer 3 hours ago.
    – paparazzo
    May 1, 2012 at 19:24
  • No I created a column on the Local Table and named the column TIME_STAMP, the datatype is smalldatetime. What I need to know now is how do I query the local table using the datetime in the TIME_STAMP column to get all records inserted or updated between this time and that time. May 1, 2012 at 20:02
  • It would be similar to the query I posted. But you should really look at timestamp as it auto increments on insert and update. SmallDateTime is only good to the minute so if there is synch then an update in the same minute then it will no resynch.
    – paparazzo
    May 1, 2012 at 20:48
  • I really appreciate your help. To your point, using actual dates will work for me better than timestamp because the table will update once or twice a day from the link table. All I need now is to create a query that says: Get all date from Local table that was created between this time and that time, or alternatively between yesterday and today. May 1, 2012 at 22:52
0

TimeStamp

TimeStamp is incremented on and insert or update.

On the Master make it a TimeStamp and on the Slave make it a Binary(8)

select [timeStampSlave].* 
from [timeStampSlave] 
join [timeStampMaster] 
on [timeStampSlave].[ID] = [timeStampMaster].ID 
and [timeStampSlave].[timeStamp] < [timeStampMaster].[timestamp]

To query across servers you can use the the following syntax

[MasterSever].[test].[dbo].[timeStampMaster]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.