2011-05-05 68 views
0

拆分的方法是有沒有辦法在SQL Server nvarchar的分裂看起來像這樣:在SQLSERVER

'some text[tag1][tag2] [tag3]' 

到:

[tag1] 
[tag2] 
[tag3] 

p.s. 我更新了示例數據以顯示沒有嚴格的分隔符。我需要將所有內容都放在括號內!

+0

'SELECT'ing? – Aliostad 2011-05-05 11:22:33

+0

你爲什麼要操縱那個級別的數據?在代碼級別執行... – 2011-05-05 11:23:39

+0

@Aliostad是的,在選擇時。 – IamDeveloper 2011-05-05 11:24:17

回答

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 
+0

,我們贏了!:)謝謝! – IamDeveloper 2011-05-05 12:06:12

+0

這是我的榮幸 – Pankaj 2011-05-05 12:12:57

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 

輸出可以像

SELECT * FROM dbo.fnSplit( '[12] [12] [13]',」「)

進行驗證

它會顯示

12 
12 
13 
+0

我不需要根據分隔符來分割... – IamDeveloper 2011-05-05 11:26:56

+0

那麼你的意思是數據將嚴格地在開始和結束方括號之間? – Pankaj 2011-05-05 11:32:50

+0

我已經發布了另一個答案。請按照它。 – Pankaj 2011-05-05 11:56:00