2010-08-16 88 views
0

如何實現下面的查詢 -執行查詢取決於選擇查詢值

SELECT 
    CASE 
     WHEN COUNT(*) > 0 THEN 
     -- UPDATE operation 
     ELSE 
     -- INSERT operation 
    END AS [RESULT] 
FROM 
    [TABLE_1] 
WHERE 
    [CONDITION] 

我使用SQL Server 2000中 有人可以幫我嗎?

回答

2

Use EXISTS not COUNT按我的答案

IF EXISTS (SELECT * FROM [TABLE_1]) 
    UPDATE [TABLE_1] SET X = Y WHERE [CONDITION] 
ELSE 
    INSERT INTO [TABLE_1] (X) VALUES (Y) 

如果您希望更新的比例非常高,那爲什麼碰桌子兩次?

UPDATE [TABLE_1] SET X = Y WHERE [CONDITION] 
IF @@ROWCOUNT = 0 
    INSERT INTO [TABLE_1] (X) VALUES (Y) 

不能爲刀片的SQL Server 2000上一個非常高的比例做同樣的:you need TRY/CATCH to handle duplicates按我的答案

1

到目前爲止做到這一點,最簡單的方法是有兩個單獨的查詢,像:

IF (SELECT COUNT(*) FROM [TABLE_1]) > 0 
    UPDATE [TABLE_1] SET X = Y WHERE [CONDITION] 
ELSE 
    INSERT INTO [TABLE_1] (X) VALUES (Y) 
+0

+1:完全同意。 – 2010-08-16 07:42:38

+1

我實際上使用EXISTS而不是數 – gbn 2010-08-16 07:45:49