简体   繁体   中英

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

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.

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