Sql Server:按顺序从表中选择,并使用相同的模式进行重新开始

时间:2013-11-18 05:16:56

标签: sql sql-server

Select RowID from MainTable
------------------------
1
2
3
4
5
6
7

我有另一个表存储一些数字的表,所以当我将这些数字作为参数传递时,我需要以下内容。所有输入和输出都在表格中。输入参数存储在输入表中。从InputTable中选择RowID。输出应来自MainTable。

Case 1:
Input:
1
2
3
Output:
4
5
6

Case 2:
Input:
4
5
6
Output:
7
1
2

Case 3:
Input:
7
1
2
Output:
3
4
5

Case 4:
Input:
3
4
5
Output:
6
7
1

.... ....

唯一的问题是,一旦到达表的末尾,就从表的顶部读取它。

输入存储在“InputTable”中 输出必须来自“MainTable”

由于

1 个答案:

答案 0 :(得分:0)

请尝试:

declare @MainTable as table(RowID int)
insert into @MainTable values (1),(2),(3),(4),(5),(6),(7)

declare @tbl as table(RowID int)
insert into @tbl values (3),(4),(5)

select RowID from @MainTable

select top 3 RowID From(
    select RowID from @MainTable where RowID>(select MAX(RowID) from @tbl)
    union all
    select RowID from @MainTable where RowID<(select MAX(RowID) from @tbl)
)x 
where RowID not in (select RowID from @tbl) //**

**注意:对于强制性3行输出,请删除此条件。