Check value if present do nothing if not present add them

Viewed 32

I have two tables History and feed. both have 103 columns 1'st column is a unique key , the second last column is checksum and the last column is Flag which tells if the row is new or updated. checksum column has a value of all the 100 columns in between the unique key and checksum. Example:

| UniqueKey | Col1 | Col2 | Col3 | CheckSum | Flag |
| --------- | ---- | ---- | ---- | -------- | ---- |
| Uk1       | A    | B    | C    | 123      | N    |
| Uk2       | D    | E    | F    | 456      | U    |
| Uk3       | G    | H    | I    | 789      | N    |
| Uk4       | J    | K    | L    | 101112   | N    |

I have 3 scenarios:

Scenario-1: if uniquekey and checksum both are present in the feed table do nothing.

Scenario-2: if UniqueKey is present but the corresponding checksum is different add the row in the feed table and add the value of the flag as U.

Scenario-3: If the combination of uniquekey and checksum is not present add the row and value of flag as N.

I tried using the while loop, in the below code i just tried to iterate through the table so that loop only runs till the count of records present in the table. but after that I am unable to use if statements to achieve the scenarios.

Declare @count int
select @count =  count(*) from [HumanResources].[Department]

declare @i int=0
while @i<=@count
begin
    declare @Name varchar(100)
    --select @Name=name from [HumanResources].[Department] where DepartmentID=@i
    if (select @Name=name from [HumanResources].[Department] where DepartmentID=@i)
    begin

    end
    set @i=@i+1
end
0 Answers
Related