简体   繁体   English

SQL Server:更新一列,如果不存在则插入

[英]SQL Server : updating one column and inserting if not exist

I have a table TableKats that looks like this: 我有一个表TableKats看起来像这样:

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 我想做的是从另一个表更新Name列,如果TableKats中不存在另一个表中的TableKats ,则应将其插入并给KatID一个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来完成此操作,因为您也不知道其他表架构,也假设Name是其他表中的列

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM