我必须改进存储过程,它在表上使用select
查询,如下所示:
SELECT DISTINCT ProjectId FROM Project where Status ='P' Order by ProjectId
它输出如下:
1
2
3
7
8
11
12
13
我需要在另一个表的insert语句中使用这些值,如下所示:
insert into Table values (othervalue, 1|1);
insert into Table values (othervalue, 2|2);
....
要减少插入次数,我们希望存储如下:
insert into Table values (othervalue, 1|3);
insert into Table values (othervalue, 7|8);
insert into Table values (othervalue, 11|13);
这是在范围内,直到没有间隙。我尝试使用CURSOR
循环遍历结果集并有一些逻辑来转换它并继续插入。但似乎有些错误。
我们可以在SELECT
查询中做些什么吗?
答案 0 :(得分:1)
with t(a,en,bg) as
(
select a,case when [begin] is NULL then NULL else row_number() over(partition by [begin] order by a) end
,case when [end] is NULL then NULL else row_number() over(partition by [end] order by a) end
from (
select t.a, case when t1.a is NULL then 'end' else NULL end [end],
case when t2.a is NULL then 'begin' else NULL end [begin]
from Project as t left join Project as t1 on (t1.a=t.a+1 AND t.Status='P' AND t1.Status='P')
left join Project as t2 on (t2.a=t.a-1 AND t2.Status='P')
) as o )
select cast(t1.a as varchar)+'|'+cast(t.a as varchar) from t inner join t as t1 on t.en=t1.bg
此查询将返回Project in' 1 | 3'中的值。类型。
您的问题是否使用plsql或sql-server并不清楚。我的解决方案适用于MS SQL Server