0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user3661240
  • 53
  • 1
  • 9
  • duplicate of http://stackoverflow.com/questions/5288283/sql-server-insert-if-not-exists-best-practice – Steve Oct 01 '14 at 21:09
  • So, for us to update a name we need to know that the name in `TableKats` is different from the one on the other table, right?, so, how do we know if we need to update it or insert it? – Lamak Oct 01 '14 at 21:14
  • Yea thats ppart of the problem :) – user3661240 Oct 01 '14 at 21:15

1 Answers1

2

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.
radar
  • 13,270
  • 2
  • 25
  • 33
  • It should just update the field if it exist, but that doens't matter anyway :) I actually also need it to delete rows in KatTable if the name doesn't exist in the other table – user3661240 Oct 01 '14 at 21:18
  • @user3661240, you can do delete also using merge – radar Oct 01 '14 at 21:20