仅当第一个选择不为空时才运行UNION SELECT

时间:2017-08-13 17:35:53

标签: sql sql-server stored-procedures

我有以下存储过程,它返回无限滚动页面的行。如何检查newTable是否为空?如果它是空的,那么我不希望执行UNION SELECT。请注意,newTable是一个非常复杂的查询,所以我不想多次执行。

@offset INT,
@fetch INT
WITH newTable AS
(
SELECT * FROM table1
ORDER BY id OFFSET @offset ROWS FETCH NEXT @fetch ROWS ONLY
)
  

如果newTable已到达最后一行且为空

,请不要运行以下命令
SELECT * FROM newTable
UNION
SELECT * FROM table3
UNION
SELECT * FROM table4
ORDER BY id

1 个答案:

答案 0 :(得分:1)

你可以这样做:

DECLARE @offset INT, 
        @fetch INT;

WITH newTable AS
(
SELECT * FROM table1
ORDER BY id OFFSET @offset ROWS FETCH NEXT @fetch ROWS ONLY
)
SELECT * 
FROM newTable
UNION
SELECT * 
FROM table3
WHERE EXISTS (SELECT 1 FROM newTable)
UNION
SELECT * 
FROM table4
WHERE EXISTS (SELECT 1 FROM newTable)
ORDER BY id

我很确定它不会再次执行cte。如果是,您可以使用临时表而不是cte:

SELECT <ColumnsList> INTO #TemporaryTable
FROM....

然后你的UNION查询。

SELECT * 
FROM #TemporaryTable
UNION
SELECT * 
FROM table3
WHERE EXISTS (SELECT 1 FROM #TemporaryTable)
UNION
SELECT * 
FROM table4
WHERE EXISTS (SELECT 1 FROM #TemporaryTable)
ORDER BY id