[英]split values separated by comma's in different lines
Hi I am trying to retrieve values from database. 嗨,我正在尝试从数据库中检索值。 I have a row which has multiple image names separated by ",".
我有一行,其中有多个用“,”分隔的图像名称。 I want to display them in different lines.
我想以不同的行显示它们。 I am using the following code which is working fine for two values.
我正在使用下面的代码,它对于两个值工作正常。 But even when I have three or more values then too it gives back only two.
但是即使我有三个或三个以上的值,它也只会返回两个。 This is my query:
这是我的查询:
;with tmp(ImageURL,HeritageId) as
(
select LEFT(ImageURL, CHARINDEX(',',ImageURL+',')-1),
STUFF(ImageURL, 1, CHARINDEX(',',ImageURL+','), '')
from shop.dbo.Images where HeritageId=@HeritageId
union all
select right(ImageURL, CHARINDEX(',',ImageURL+',')-1),
STUFF(ImageURL, 1, CHARINDEX(',',ImageURL+','), '')
from Images
where ImageURL > '' and HeritageId=@HeritageId
)
select ImageURL
from tmp
Your query looks like an attempt to use a recursive CTE to split a string. 您的查询看起来像是尝试使用递归CTE拆分字符串。 It that is the case it should look something like this.
就是这种情况,它应该看起来像这样。
;with tmp(ImageURL,Rest) as
(
select LEFT(ImageURL, CHARINDEX(',',ImageURL+',')-1),
STUFF(ImageURL, 1, CHARINDEX(',',ImageURL+','), '')
from Images where HeritageId=@HeritageId
union all
select LEFT(Rest, CHARINDEX(',',Rest+',')-1),
STUFF(Rest, 1, CHARINDEX(',',Rest+','), '')
from tmp
where Rest > ''
)
select ImageURL
from tmp
Use the CTE in the recursive part instead of the table. 在递归部分而不是表中使用CTE。
I would suggest using (and marking) the answer suggested by @Mikael, however if your sequence only has 4 values then you can use the PARSENAME
function to split on a period. 我建议使用(并标记)@Mikael提出的答案,但是,如果您的序列只有4个值,则可以使用
PARSENAME
函数在一个时间段上拆分。
DECLARE @test TABLE
(
[CSVColumn] NVARCHAR(MAX) NOT NULL
)
INSERT INTO @test VALUES ('The PARSENAME function splits on a period.But can only hold.Four.Values - any more and it will return null')
SELECT PARSENAME([CSVColumn], 4) AS 'Col1',
PARSENAME([CSVColumn], 3) AS 'Col2',
PARSENAME([CSVColumn], 2) AS 'Col3',
PARSENAME([CSVColumn], 1) AS 'Col4'
FROM @test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.