2012-07-17 151 views
2

可能重複:
Solutions for INSERT OR UPDATE on SQL ServerSQL查詢中包含if/else語句

我在,我想編寫一個SQL查詢,包括條件語句一個很大的麻煩。

EG:我有一個SQL表,其列ID,NAME,STATUS,所以在我插入值到這個表之前我想檢查表中已經存在的名稱。如果它存在,那麼我想更新狀態值。

是否有可能通過使用queryString(SQL Server查詢,而不是存儲過程)方法編寫查詢,如果有人know pls幫助我。我使用SQL Server 2008 R2的

回答

3

你想要MERGE查詢語法

從文檔(http://technet.microsoft.com/en-us/library/bb510625.aspx

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 
2

以下是可能的方式:

1)用 '存在'方法

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

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)未經編譯的查詢(構建查詢)

--Unable to post on S.O.F due to security limitations 

雖然所提出的方法是第一&第二(第三是不必要)。

0

你想要的東西像

IF EXISTS (SELECT Name FROM YourDatabase WHERE [_SomeCondition_]) 
BEGIN 
    INSERT INTO YourTable (Status) 
    SELECT OtherStatus AS Status 
    FROM SomeOtherTable 
END 

就是這樣。

我希望這會有所幫助。