I am creating a stored procedure where I am inserting into a table from a SELECT statement. The table has 4 columns (e.g. Col1, Col2, Col3, Col4). Column1 has a unique value. and Column4 is the timestamp of when the rows are inserted.
What I want to achieve is this:-
1.) That when I run the stored procedure on a later date lets say on the 20032017 I add the rows to the table if Col1 does not exists in the table.
2.) If Col1 already exists in the table I update the values of Col2 and Col3 while keeping tha value of Col5 as is.
So assuming in the second run of the stored procedure the select statement returns this dataset.
The table will show like this, Rows with Col1 value of 7 is inserted in the table. Rows with Col1 values of 1, 2, and 3 have the values of Col2 and Col3 updated while Col4 remain with the same value.
Probably I have to create a loop in the stored procedure where each row in the dataset returned by the SELECT statement is processed but I am new to stored procedures and I am having difficulties. Code examples are much appreciated so I can understand better.
Thanks
MERGE- sounds like what you need. msdn.microsoft.com/en-us/library/bb510625.aspx