1

我只想知道如何使用从带有字符串分隔符的列中选择来获取值。

例如:列值为:

    ';#10;~Banana;#101;~Apple'

我怎样才能得到这些值并保存在这样的表中?

    code   description
    10     Banana
    101    Apple

似乎无法使用子字符串、charindex 组合来获取它。我应该改用函数吗?基本上,此列有可能存储 100 多个值(代码/说明)。

4

3 回答 3

2

尝试使用 XML 节点方法 ( SQL-FIDDEL )

DECLARE @S VARCHAR(500)= ';#10;~Banana;#101;~Apple'

--REMOVE LEADING ROW DELIMETER `;#`
SELECT @S = SUBSTRING(@S,3, LEN(@S))


DECLARE @X XML 
SELECT @X  = '<myxml><nodes><n1>' + 
REPLACE(REPLACE (@S,';#','</n2></nodes><nodes><n1>'),';~','</n1><n2>') + 
'</n2></nodes></myxml>'


SELECT C.value('n1[1]','VARCHAR(50)') AS code,
       C.value('n2[1]','VARCHAR(50)') AS description
FROM @X.nodes('/myxml/nodes') Cols (C)


| CODE | DESCRIPTION |
----------------------
|   10 |      Banana |
|  101 |       Apple |
于 2013-06-03T12:15:03.587 回答
0

或简单的子字符串';'

select 
   substr( column, INSTR(column, ';', 1, 1)+1, 
   (INSTR(column, ';', 1, 2 ) - INSTR(column, 1, 1 ))
   ) col_a,
   substr( column, INSTR(column, ';', 1, 2)+1, 
   (INSTR(column, ';', 1, 3 ) - INSTR(column, ';', 1, 2 ))
   ) col_b
from dual

工作示例:

select 
   substr( ';#10;~Banana;#101;~Apple', INSTR(';#10;~Banana;#101;~Apple', ';', 1, 1)+1, 
    (INSTR(';#10;~Banana;#101;~Apple', ';', 1, 2 ) - INSTR(';#10;~Banana;#101;~Apple', ';', 1, 1 ))
   ) col_a,
   substr( ';#10;~Banana;#101;~Apple', INSTR(';#10;~Banana;#101;~Apple', ';', 1, 2)+1, 
   (INSTR(';#10;~Banana;#101;~Apple', ';', 1, 3 ) - INSTR(';#10;~Banana;#101;~Apple', ';', 1, 2 ))
   ) col_b
from dual
于 2013-06-03T12:25:37.327 回答
0

你可以试试上面的(而不是','使用';'):

CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000) -- List of delimited items
  , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (item 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 -- Put the last item in
RETURN
END
GO



select * from dbo.fnSplit('1,22,333,444,,5555,666', ',')

Results

Item

1
22
333
444
5555
666
于 2013-06-03T11:40:46.320 回答