CREATE TABLE tb(ID int,Num int)
INSERT tb SELECT 1,2
UNION ALL ALL SELECT 6,2
UNION ALL SELECT 7,1
UNION ALL SELECT 8,5
UNION ALL SELECT 9,1
GO
--查询的存储过程
CREATE PROC p_Qry
@group VARCHAR(1000)
AS
SET NOCOUNT ON
IF @group LIKE '%[^0-9,]%'
BEGIN
RAISERROR(N'"%s" 中包含非数字数据',1,16,@group)
RETURN
END
--将字符串分拆为分组表
DECLARE @t TABLE(ID int IDENTITY,Groups varchar(10),a int,b int)
DECLARE @i int,@pid varchar(10)
SELECT @i=CHARINDEX(',',@group+',')
,@pid=LEFT(@group,@i-1)
,@group=STUFF(@group,1,@i,'')+','
,@i=CHARINDEX(',',@group)
INSERT @t SELECT 'ID<='+@pid,NULL,@pid
WHILE @i>1
BEGIN
INSERT @t SELECT @pid+'<ID<='+LEFT(@group,@i-1),@pid,LEFT(@group,@i-1)
SELECT @pid=LEFT(@group,@i-1)
,@group=STUFF(@group,1,@i,'')
,@i=CHARINDEX(',',@group)
END
INSERT @t SELECT 'ID>'+@pid,@pid,NULL
--根据分组表统计
SELECT b.Groups,Num=ISNULL(SUM(a.Num),0)
FROM tb a RIGHT JOIN @t b
ON (a.ID<=b.b OR b.b IS NULL)
AND(a.ID>b.a OR b.a IS NULL)
GROUP BY b.ID,b.Groups
ORDER BY b.ID
GO
--调用存储过程进行查询
EXEC p_Qry '2,3,6'
/*--测试结果
Groups Num
---------- -----------
ID<=2 5
2<ID<=3 2
3<ID<=6 16
ID>6 7
--*/
INSERT tb SELECT 1,2
UNION ALL ALL SELECT 6,2
UNION ALL SELECT 7,1
UNION ALL SELECT 8,5
UNION ALL SELECT 9,1
GO
--查询的存储过程
CREATE PROC p_Qry
@group VARCHAR(1000)
AS
SET NOCOUNT ON
IF @group LIKE '%[^0-9,]%'
BEGIN
RAISERROR(N'"%s" 中包含非数字数据',1,16,@group)
RETURN
END
--将字符串分拆为分组表
DECLARE @t TABLE(ID int IDENTITY,Groups varchar(10),a int,b int)
DECLARE @i int,@pid varchar(10)
SELECT @i=CHARINDEX(',',@group+',')
,@pid=LEFT(@group,@i-1)
,@group=STUFF(@group,1,@i,'')+','
,@i=CHARINDEX(',',@group)
INSERT @t SELECT 'ID<='+@pid,NULL,@pid
WHILE @i>1
BEGIN
INSERT @t SELECT @pid+'<ID<='+LEFT(@group,@i-1),@pid,LEFT(@group,@i-1)
SELECT @pid=LEFT(@group,@i-1)
,@group=STUFF(@group,1,@i,'')
,@i=CHARINDEX(',',@group)
END
INSERT @t SELECT 'ID>'+@pid,@pid,NULL
--根据分组表统计
SELECT b.Groups,Num=ISNULL(SUM(a.Num),0)
FROM tb a RIGHT JOIN @t b
ON (a.ID<=b.b OR b.b IS NULL)
AND(a.ID>b.a OR b.a IS NULL)
GROUP BY b.ID,b.Groups
ORDER BY b.ID
GO
--调用存储过程进行查询
EXEC p_Qry '2,3,6'
/*--测试结果
Groups Num
---------- -----------
ID<=2 5
2<ID<=3 2
3<ID<=6 16
ID>6 7
--*/