user3661240
user3661240

Reputation: 53

SQL Server : updating one column and inserting if not exist

I have a table TableKats that looks like this:

ID - int 
Name - varchar
KatID - int 

What I want to do is to update the column Name from another table, and if there is a name in the other table that doesn't exist in TableKats, it should insert it and give KatID a 0

Does anybody know a way to do that? Thanks

Upvotes: 0

Views: 99

Answers (1)

radar
radar

Reputation: 13425

you can do it using MERGE, as your other table schema is not known assuming Name as the column in other table too

MERGE TableKats T
USING ( SELECT * from TableB) AS S
ON T.Name = S.Name
WHEN NOT MATCHED THEN
  INSERT ( Name, KatID)
  VALUES ( S.Name, 0)
WHEN MATCHED THEN
  UDPATE  -- Not clear what needs to be updated.

Upvotes: 2

Related Questions