我得到像这样的表类型变量
color
-------------
Black
Blue<br/>PMS 285C
Green<br/>PMS 360
Red<br/>PMS 199
我想让它们像
color
-------------
Black, Blue, Green, Red
但是我很难删除“&amp; lt ..”的东西。 我按照这个答案:Is there a way to loop through a table variable in TSQL without using a cursor? 要创建临时表以循环和删除字符,但仍然无法正常工作
DECLARE @result int, @i int = 0, @colors varchar(800);
DECLARE @results table(color varchar(40));
INSERT INTO @results SELECT color FROM...
DECLARE @temp table(Id INT, color varchar(40));
INSERT INTO @temp SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Id, color FROM @results
WHILE (SELECT Count(*) FROM @temp WHERE color like '%<%') > 0
BEGIN
SELECT Top 1 @i = Id FROM @temp WHERE color like '%<%'
UPDATE @temp Set color = (case when color like '%<%'
then left(color, charindex('<', color) - 1)
else color
end) Where Id = @i
Delete @temp Where Id = @i
END
我还是
color
------------------------------------------------------------------------------
Black, Blue<br/>PMS 285C, Green<br/>PMS 360, Red<br/>PMS 199
有人可以帮我吗?或者提出一些建议。
由于
答案 0 :(得分:0)
这会使用left()
和charindex()
来获取每个值的左侧部分
在&
之前;并使用stuff()
with select ... for xml path ('')
method of string concatenation。
select stuff((
select ', '+left(color,charindex('&',color+'&')-1)
from @temp
for xml path (''), type).value('.','varchar(max)')
,1,2,'')
测试设置:
create table temp (color varchar(32))
insert into temp values
('Black')
,('Blue<br/>PMS 285C')
,('Green<br/>PMS 360')
,('Red<br/>PMS 199')
select stuff((
select ', '+left(color,charindex('&',color+'&')-1)
from temp
for xml path (''), type).value('.','varchar(max)')
,1,2,'')
返回:Black, Blue, Green, Red
rextester演示:http://rextester.com/TWESQZ38491
参考:
答案 1 :(得分:0)
基于先前答案的另一个版本
create table temp (color varchar(32))
insert into temp values
('Black')
,('Blue<br/>PMS 285C')
,('Green<br/>PMS 360')
,('Red<br/>PMS 199')
declare @var varchar(max)
set @var=''
select @var=@var+case when charindex('&',color)=0 then color
else left(color, charindex('&',color)-1) end +', ' from temp
select left(@var, len(@var)-1)