我有一个存储过程接收TVP作为输入。现在,我需要检查主键列中特定ID的接收数据。如果它存在,那么我只需要使用其他列的新值(通过TVP发送)更新表。否则,请插入。
怎么做?
CREATE PROCEDURE ABC
@tvp MyTable READONLY
AS
IF EXISTS (SELECT 1 FROM MYTAB WHERE ID= @tvp.ID)
DO update
ELSE
Create
只是想知道我所做的if exists
循环是正确的。我认为这是错误的,因为它只检查第一个值然后更新。其他价值怎么样?我该怎么做呢?
答案 0 :(得分:0)
循环/ CURSOR是最后的武器,总是搜索SET based
而不是ROW based
的解决方案。
您应该使用专为此类操作设计的MERGE:
MERGE table_name AS TGT
USING (SELECT * FROM @tvp) AS SRC
ON TGT.id = SRC.ID
WHEN MATCHED THEN
UPDATE SET col = SRC.col
WHEN NOT MATCHED THEN
INSERT (col_name, col_name2, ...)
VALUES (SRC.col_name1, SRC.col_name2, ...)
如果你不喜欢MERGE,请使用INSERT / UPDATE:
UPDATE table_name
SET col = tv.col,
...
FROM table_name AS tab
JOIN @tvp AS tv
ON tab.id = tv.id
INSERT INTO table_name(col1, col2, ...)
SELECT tv.col1, tv.col2, ...
FROM table_name AS tab
RIGHT JOIN @tvp AS tv
ON tab.id = tv.id
WHERE tab.id IS NULL