根据选择的查询值执行查询

时间:2010-08-16 07:39:29

标签: sql sql-server-2000

如何实现以下查询 -

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

我正在使用SQL Server 2000。 有人可以帮助我吗?

2 个答案:

答案 0 :(得分: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上的很大比例的INSERT,你不能这样做:you need TRY/CATCH to handle duplicates根据我的回答

答案 1 :(得分:1)

到目前为止,最简单的方法是使用两个单独的查询,例如:

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