我有两个选择查询
这两个查询来自同一个表,但查询条件不能共存。
我该怎么做?
答案 0 :(得分:1)
您可以尝试使用@@ ROWCOUNT ...
IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
DROP TABLE #TestData;
CREATE TABLE #TestData (
SomeNumber INT NOT NULL
);
INSERT #TestData (SomeNumber) VALUES (1), (2), (3), (4), (5);
--=====================================================
SELECT * FROM #TestData td WHERE td.SomeNumber = 22;
IF @@ROWCOUNT = 0
BEGIN
SELECT * FROM #TestData td WHERE td.SomeNumber <= 5;
END;
答案 1 :(得分:0)
使用IF ELSE
IF ((SELECT COUNT(1) FROM table_name WHERE condition_1 ) = 0)
SELECT col_1, col_2, ... col_n FROM table_name WHERE condition_2
ELSE
SELECT col_1, col_2, ... col_n FROM table_name WHERE condition_1
答案 2 :(得分:0)
这将检查query1是否有结果并将其设置为变量。如果ELSE将检查是否有query1的结果,那么query1否则query2
DECLARE @rec_cnt INT
SET @rec_cnt = (SELECT 1
FROM table
WHERE condition1)
IF @rec_cnt IS NOT NULL
(SELECT *
FROM table
WHERE condition1);
ELSE
(SELECT *
FROM table
WHERE condition2);
答案 3 :(得分:0)
IF EXISTS (SELECT TOP 1 1 FROM table1 WHERE condition1)
SELECT col_1, col_2 FROM table1 WHERE condition1
ELSE
SELECT col_1, col_2 FROM table1 WHERE condition2