求SQL 语句,以逗号为分隔
DECLARE @xx VARCHAR(100) ,
@yy VARCHAR(100)
set @xx='ds,B,cee,d,' --以逗号为分隔的字符串
set @yy='122,24,3,4,'
怎么写一个循环语句,得到
当输出ds时,同时输出122
当输出B时,同时输出24
~
一一对应,输出的值用做调用
[解决办法]
这个需要建个函数
/*
DROP FUNCTION dbo.Split
SELECT dbo.Split
*/
CREATE FUNCTION dbo.Split
(
@SplitString varchar(8000),-- nvarchar(4000)
@Separator varchar(2) = ','
)
RETURNS @SplitStringsTable TABLE
(
[id] int identity(1,1),
[value] varchar(8000)-- nvarchar(4000)
)
AS
BEGIN
DECLARE @CurrentIndex int;
DECLARE @NextIndex int;
DECLARE @ReturnText varchar(8000);-- nvarchar(4000)
SELECT @CurrentIndex=1;
WHILE(@CurrentIndex<=len(@SplitString))
BEGIN
SELECT @NextIndex=charindex(@Separator,@SplitString,@CurrentIndex);
IF(@NextIndex=0 OR @NextIndex IS NULL)
SELECT @NextIndex=len(@SplitString)+1;
SELECT @ReturnText=substring(@SplitString,@CurrentIndex,@NextIndex-@CurrentIndex);
INSERT INTO @SplitStringsTable([value])
VALUES(@ReturnText);
SELECT @CurrentIndex=@NextIndex+1;
END
RETURN;
END
DECLARE @xx VARCHAR(100) ,@yy VARCHAR(100)
set @xx='ds,B,cee,d,' --以逗号为分隔的字符串
set @yy='122,24,3,4,'
declare @s varchar(10)
set @s='ds'
select b.value
from dbo.split(@xx,',') a
inner join dbo.split(@yy,',') b on a.id=b.id
where a.value=@s
/*
122
*/
DECLARE @xx VARCHAR(100) ,@yy VARCHAR(100)
set @xx='ds,B,cee,d,' --以逗号为分隔的字符串
set @yy='122,24,3,4,'
declare @s varchar(10)
set @s='B'
select b.value
from dbo.split(@xx,',') a
inner join dbo.split(@yy,',') b on a.id=b.id
where a.value=@s
/*
24
*/
DECLARE @xx VARCHAR(100) ,
@yy VARCHAR(100)
set @xx='ds,B,cee,d,'
set @yy='122,24,3,4,'
SELECT b.*
FROM
(
SELECT
xx=CONVERT(XML, '<root><v>'+replace(xx,',','</v><v>')+'</v></root>'),
yy=CONVERT(XML, '<root><v>'+replace(yy,',','</v><v>')+'</v></root>')
FROM (SELECT xx = LEFT(@xx, LEN(@xx)-1), yy=LEFT(@yy, LEN(@yy)-1)) t
) a
OUTER APPLY
(
SELECT m.rowid,m.xx,n.yy FROM
(
SELECT rowid = ROW_NUMBER() OVER(ORDER BY GETDATE()), xx = C.v.value('.','NVARCHAR(MAX)')
FROM a.xx.nodes('/root/v') C(v)
) m
INNER join
(
SELECT rowid = ROW_NUMBER() OVER(ORDER BY GETDATE()), yy = C.v.value('.','NVARCHAR(MAX)')
FROM a.yy.nodes('/root/v') C(v)
) n
ON m.rowid = n.rowid
) b
/*
rowidxxyy
1ds122
2B24
3cee3
4d4
*/