拆分的方法是有没有办法在SQL Server nvarchar的分裂看起来像这样:在SQLSERVER
'some text[tag1][tag2] [tag3]'
到:
[tag1]
[tag2]
[tag3]
?
p.s. 我更新了示例数据以显示没有严格的分隔符。我需要将所有内容都放在括号内!
拆分的方法是有没有办法在SQL Server nvarchar的分裂看起来像这样:在SQLSERVER
'some text[tag1][tag2] [tag3]'
到:
[tag1]
[tag2]
[tag3]
?
p.s. 我更新了示例数据以显示没有严格的分隔符。我需要将所有内容都放在括号内!
下面尝试。
declare @v varchar(1000)
set @v = '[1212][12121212] [[['
create table #temp
(
v varchar(1000)
)
--insert into #temp(v)values(@v)
declare @Firstindex int
declare @Secondindex int
declare @subval varchar(100)
Set @Firstindex = charindex('[', @v, 1)
while(@Firstindex <> 0)
Begin
Set @Firstindex = charindex('[', @v, @Firstindex)
if(@Firstindex = 0)
break
Set @Secondindex = charindex(']', @v, @Firstindex)
if(@Secondindex = 0)
break;
if(@Firstindex + 1 <> @Secondindex)
Begin
set @subval = substring(@v, @Firstindex + 1, (@Secondindex - 1) - (@Firstindex))
select @subval
Insert into #temp values(@subval)
End
set @Firstindex = @Secondindex
End
select * from #temp
drop table #temp
,我们赢了!:)谢谢! – IamDeveloper 2011-05-05 12:06:12
这是我的荣幸 – Pankaj 2011-05-05 12:12:57
可以使用下面的函数
CREATE FUNCTION [dbo].[fnSplit](
@sInputList VARCHAR(8000)
, @sDelimiter VARCHAR(8000) = ','
) RETURNS @List TABLE (ID VARCHAR(8000))
BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN
SELECT
@sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
@sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
IF LEN(@sItem) > 0
INSERT INTO @List SELECT @sItem
END
IF LEN(@sInputList) > 0
INSERT INTO @List SELECT @sInputList
RETURN
END
输出可以像
SELECT * FROM dbo.fnSplit( '[12] [12] [13]',”“)
进行验证它会显示
12
12
13
我不需要根据分隔符来分割... – IamDeveloper 2011-05-05 11:26:56
那么你的意思是数据将严格地在开始和结束方括号之间? – Pankaj 2011-05-05 11:32:50
我已经发布了另一个答案。请按照它。 – Pankaj 2011-05-05 11:56:00
'SELECT'ing? – Aliostad 2011-05-05 11:22:33
你为什么要操纵那个级别的数据?在代码级别执行... – 2011-05-05 11:23:39
@Aliostad是的,在选择时。 – IamDeveloper 2011-05-05 11:24:17