0

如何通过sqlsever中的SQL按某个关键字拆分内容?

我有两个表,t1 和 t2,我想用 t1 中的单词拆分 t2 中的某些列。

t1
column1
a
bc
c
z

t2(based)
column1 column2
1        abcrrr    
2        cdt
3        e


t2(updated)
column1 column2
1        a
1        bc
1        rrr
2        c
2        dt
3        e

是否可以像上面那样编写一个 SQL 语句来更新 t2 ?我想要 SQLserver 2008 中的这种性能。

逻辑是,如果 t1.column1 中的数据是某个 t2.column2 的 subString,则将 t2.column2 拆分为两个新行,t2.column1 相同,但是对于新行的 t2.column2,一个是 subString ,其他是其余的(删除了 sutStr)。

谢谢!哇哇

4

4 回答 4

1
declare @t table(column1 int, column2 varchar(100))
insert into @t 
select 1,        'ab' union all     
select 2,        'cd' union all 
select 3,        'e' 

 select t1.column1,char(t2.number) as columns2 from @t as t1 
 inner join master..spt_values as t2 on t1.column2 like '%'+char(t2.number)+'%'
 where type='p' and number between 97 and  97+25
于 2012-07-20T09:26:28.603 回答
0

您可以尝试使用任何字符集。

declare @t table(column1 int, column2 varchar(100))
insert into @t 
select 1,        'abc' union all     
select 2,        'cd' union all 
select 3,        'eyiuyiu' 
select * from @t
;WITH CTE as (
select column1,CASE when len(column2) >= 0 then left(column2,1) else column2 end as column2,RIGHT(column2,len(column2)-1) as rem from @t --where column1 = 1
union all
select t1.column1,CASE when len(rem) >= 0 then left(rem,1) else rem end as column2,RIGHT(rem,len(rem)-1) as rem from CTE c inner join @t t1
on c.column1=t1.column1 and CHARINDEX(c.rem,t1.column2,1) > 0
 )
select column1,column2 from cte order by 1
于 2012-07-20T10:30:32.150 回答
0

select t2.column1,t1.column1 from t1
inner join t2 on t1.column1 like '%['+ t2.column2 +']%'

于 2012-07-20T10:56:01.933 回答
0

首先创建函数

CREATE FUNCTION FN_COL_SPLIT(@COL VARCHAR(200))
RETURNS @TPARTS TABLE ( PART VARCHAR(20) )
AS
BEGIN

;WITH CTE ( RNK ,AUTOID,COLUMN1,COL,SLNO)AS (
SELECT  ROW_NUMBER() OVER(ORDER BY T1.AUTOID) AS RNK,T1.AUTOID,T1.COLUMN1,REPLACE(@COL,T1.COLUMN1,'') AS COL,0 FROM T1  
WHERE (LEN(REPLACE(@COL,T1.COLUMN1,''))<>LEN(@COL))   
UNION ALL
SELECT   ROW_NUMBER() OVER(ORDER BY T1.AUTOID) AS RNK,T1.AUTOID,T1.COLUMN1 ,REPLACE(COL,T1.COLUMN1,'') AS COL,SLNO+1 FROM CTE C   JOIN T1 
ON LEN(REPLACE(COL,T1.COLUMN1,''))<>LEN(COL)      )
INSERT INTO @TPARTS
SELECT DISTINCT COLUMN1 FROM CTE  WHERE RNK=1
UNION 
SELECT COL FROM CTE WHERE LEN(COL)=(SELECT MIN(LEN(COL)) FROM CTE)

IF (SELECT COUNT(*) FROM  @TPARTS)=0 INSERT INTO @TPARTS SELECT @COL

RETURN
END

然后使用下面的select语句得到结果

SELECT T2.COLUMN1,T3.PART FROM T2 CROSS APPLY FN_COL_SPLIT(T2.COLUMN2) T3
于 2012-07-24T10:24:54.910 回答