有没有办法在sql server nvarchar中拆分,如下所示:
'some text[tag1][tag2] [tag3]'
成:
[tag1]
[tag2]
[tag3]
P.S。 我更新了示例数据以显示,没有严格的分隔符。我需要把所有内容都放在括号内!
答案 0 :(得分:1)
请尝试以下。
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
答案 1 :(得分:0)
您可以使用以下功能
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
输出可以像
一样进行验证从dbo.fnSplit中选择*('[12] [12] [13]','')
会显示
12
12
13