日期:2014-05-18 浏览次数:20525 次
3.5.2 字符串并集&交集处理示例.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
create table tb1(Item varchar(20),Name char(1)) insert tb1 values('1,3,7,11','A') insert tb1 values('3,5,9','B') insert tb1 values('1,9,14','C') create table tb2(No int,Name varchar(20)) insert tb2 values(1,'abc') insert tb2 values(2,'dfe') insert tb2 values(3,'ffe') go create table tt(Item varchar(20)) DECLARE @t TABLE(ID int identity,b bit) INSERT @t(b) SELECT TOP 20 0 FROM sys.columns a INSERT INTO tt(Item) SELECT distinct s FROM( SELECT s=SUBSTRING(a.Item,b.ID,CHARINDEX(',',a.Item+',',b.ID)-b.ID) FROM tb1 a,@t b WHERE b.ID<=LEN(a.Item) AND SUBSTRING(','+a.Item,b.ID,1)=',' GROUP BY SUBSTRING(a.ITem,b.ID,CHARINDEX(',',a.ITem+',',b.ID)-b.ID) ) a --select * from tt /* Item -------------------- 1 11 14 3 5 7 9 (7 row(s) affected) */ drop table tb1,tb2,tt