字符串并集&交集处理示例.sql
--示例数据
CREATE TABLE tb(ID int,col varchar(50))
INSERT tb SELECT 1,'1,2,3,4'
UNION ALL SELECT 1,'1,3,4'
UNION ALL SELECT 1,'1,4'
UNION ALL SELECT 2,'11,3,4'
UNION ALL SELECT 2,'1,33,4'
UNION ALL SELECT 3,'1,3,4'
GO
--1. 字符串并集处理函数
CREATE FUNCTION dbo.f_mergSTR(@ID int)
RETURNS varchar(50)
AS
BEGIN
DECLARE @t TABLE(ID int identity,b bit)
--分拆处理辅助表,由于列col的最大宽度为50,所以只需要1到50的分拆辅助记录
INSERT @t(b) SELECT TOP 50 0
FROM syscolumns
DECLARE @r varchar(50)
SET @r=''
SELECT @r=@r+','+s
FROM(
SELECT s=SUBSTRING(a.col,b.ID,CHARINDEX(',',a.col+',',b.ID)-b.ID)
FROM tb a,@t b
WHERE a.ID=@ID
AND b.ID<=LEN(a.col)
AND SUBSTRING(','+a.col,b.ID,1)=','
GROUP BY SUBSTRING(a.col,b.ID,CHARINDEX(',',a.col+',',b.ID)-b.ID)
)a ORDER BY s
RETURN(STUFF(@r,1,1,''))
END
GO
--调用用户定义实现交并集查询
SELECT ID,col=dbo.f_mergSTR(ID)
FROM tb
GROUP BY ID
GO
/*================================================================*/
--2. 字符串交集处理函数
CREATE FUNCTION dbo.f_mergSTR(@ID int)
RETURNS varchar(50)
AS
BEGIN
DECLARE @t TABLE(ID int identity,b bit)
--分拆处理辅助表,由于列col的最大宽度为50,所以只需要1到50的分拆辅助记录
INSERT @t(b) SELECT TOP 50 0
FROM syscolumns
DECLARE @r varchar(50)
SET @r=''
SELECT @r=@r+','+s
FROM(
SELECT s=SUBSTRING(a.col,b.ID,CHARINDEX(',',a.col+',',b.ID)-b.ID)
FROM tb a,@t b
WHERE a.ID=@ID
AND b.ID<=LEN(a.col)
AND SUBSTRING(','+a.col,b.ID,1)=','
GROUP BY SUBSTRING(a.col,b.ID,CHARINDEX(',',a.col+',',b.ID)-b.ID)
HAVING COUNT(*)=(SELECT COUNT(*) FROM tb WHERE ID=@ID))a
RETURN(STUFF(@r,1,1,''))
END
GO
--调用用户定义实现交交集查询
SELECT ID,col=dbo.f_mergStr(ID)
FROM tb
GROUP BY ID
GO