日期:2014-05-18  浏览次数:20525 次

如何处理(1,3,5,9)这样的字段?
我两个表,一个如下
Item Name
1,3,7,11 A
3,5,9 B
1,9,14 C

另外一个
NO Name
1 abc
2 dfe
3 ffe
...

现在需要把第一个表中的1,3,7,11 3,5,9 1,9,14 去除“,”号,然后分别按照1,3,7,11,3,5,1,9,14取出来,之后取非重复值得到1,3,5,7,9,11,14之后,与第二个表做join。

如何实现啊?


------解决方案--------------------
SQL code
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

------解决方案--------------------
SQL code
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