获取和偏移后的UNION SELECT

时间:2017-07-25 16:41:37

标签: sql sql-server stored-procedures

我有以下存储过程:

@offset INT,
@fetch INT

SELECT col1 AS col FROM tab1
UNION
SELECT col1 FROM tab2
ORDER BY col OFFSET @offset ROWS FETCH NEXT @fetch ROWS ONLY

现在我想在执行offset和fetch之后添加第三个表作为UNION。这可能吗?

UNION
SELECT TOP 1 col1 FROM tab3
ORDER BY NEWID() 

2 个答案:

答案 0 :(得分:2)

使用派生表

$oldFunction

注意:如果您不想删除结果中的重复项,则可以将Select col from ( SELECT col1 AS col FROM tab1 UNION SELECT col1 FROM tab2 ORDER BY col OFFSET @offset ROWS FETCH NEXT @fetch ROWS ONLY ) a UNION SELECT TOP 1 col1 FROM tab3 ORDER BY NEWID() 替换为UNION

答案 1 :(得分:2)

@offset INT,
@fetch INT

WITH CTE1
AS
(SELECT TOP 100 PERCENT col1 AS col FROM tab1
UNION
SELECT TOP 100 PERCENT col1 FROM tab2
ORDER BY col OFFSET @offset ROWS FETCH NEXT @fetch ROWS ONLY)

SELECT * FROM CTE1
UNION
SELECT TOP 1 col1 FROM tab3
ORDER BY NEWID()