Using Case statement to either Insert into a table or Update an existing row
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Solutions for INSERT OR UPDATE on SQL Server
Only inserting a row if it's not already there
我的标题几乎解释了我正在尝试做什么,但我会详细介绍一下。 我正在调用它时创建一个存储过程,首先检查该行是否已存在(通过比较两个参数),如果存在,它将更新行中的特定列,如果该行不存在则 将在表中插入一个新行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | BEGIN SELECT ( CASE WHEN [Site] = @site AND Plant = @plant THEN UPDATE [STATUS] FROM Server_Status WHERE [Site] = @site ELSE INSERT INTO Server_Status(Name, [Path], [Site], Plant, [STATUS]) VALUES (@name, @path, @site, @plant, @STATUS) END ) FROM Server_Status END |
是我到目前为止,但不起作用(显然)。 有没有比我有任何建议的SQL知识的人?
-J
您可能希望查看MERGE(Transact-SQL)语句。
Performs insert, update, or delete operations on a target table based
on the results of a join with a source table. For example, you can
synchronize two tables by inserting, updating, or deleting rows in one
table based on differences found in the other table.
你可以做:
1 2 3 4 5 6 7 8 9 10 | IF EXISTS(SELECT * FROM MyTable WHERE...) --value exists perform update BEGIN UPDATE... END ELSE --value doesnt exist perform insert BEGIN INSERT ... END |
您应首先使用IF EXISTS语句检查行是否存在,如下所示:
1 2 3 4 5 6 7 | IF EXISTS (SELECT * FROM Server_Status WHERE Site = @Site) BEGIN -- UPDATE statement. END ELSE -- INSERT statement. END |