SQL query contains IF / ELSE statement
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Solutions for INSERT OR UPDATE on SQL Server
我非常麻烦,我想写一个包含条件语句的SQL查询。
EG:我有一个列
是否可以使用queryString(SQL Server查询而不是存储过程)方法编写查询,如果有人知道请帮助我。 我正在使用SQL Server 2008 R2
您需要
从文档(http://technet.microsoft.com/en-us/library/bb510625.aspx)
1 2 3 4 5 6 7 8 9 | MERGE Production.UnitMeasure AS target USING (SELECT @UnitMeasureCode, @Name) AS SOURCE (UnitMeasureCode, Name) ON (target.UnitMeasureCode = SOURCE.UnitMeasureCode) WHEN MATCHED THEN UPDATE SET Name = SOURCE.Name WHEN NOT MATCHED THEN INSERT (UnitMeasureCode, Name) VALUES (SOURCE.UnitMeasureCode, SOURCE.Name) OUTPUT deleted.*, $action, inserted.* INTO #MyTempTable |
以下是可能的方法:
1)使用'EXISTS'方法
1 2 3 4 | IF EXISTS(SELECT 1 FROM Table1 WHERE Name = @Name) UPDATE Table1 SET STATUS = @STATUS WHERE Name = @Name ELSE INSERT INTO Table1 (Name, STATUS) VALUES(@Name, @STATUS) |
2)使用MERGE
1 2 3 4 5 6 7 8 | MERGE Table1 AS TARGET USING (SELECT @Name, @STATUS FROM Table1) AS SOURCE (Name, STATUS) ON (TARGET.Name = SOURCE.Name) WHEN MATCHED THEN UPDATE SET STATUS = SOURCE.Status WHEN NOT MATCHED THEN INSERT (Name, STATUS) VALUES (SOURCE.Name, SOURCE.Status) |
3)未编译的查询(构建查询)
1 | --Unable to post on S.O.F due to security limitations |
虽然建议的方法是第一和第二 第2次(第3次不需要)。
你想要的东西
1 2 3 4 5 6 | IF EXISTS (SELECT Name FROM YourDatabase WHERE [_SomeCondition_]) BEGIN INSERT INTO YourTable (STATUS) SELECT OtherStatus AS STATUS FROM SomeOtherTable END |
而已。
我希望这有帮助。