如何从字符串中获取值

时间:2013-02-05 16:31:57

标签: sql tsql

如何从列A中使用

从查询sql中获取代码和子代码

格式:

[very long name | code | subcode] 

示例

[Pear | S01 | 10]
[Pineapple | S01 | 9]

PS:没有方括号,但管道分隔符是真实的

2 个答案:

答案 0 :(得分:3)

试试这个; DEMO - UPDATED WITH A TABLE

--declare @s varchar(50)='[Pineapple | S01 | 9]'

select substring(yourColumn,ind1 + 1,ind2-(ind1 +1)) code, 
       substring(yourColumn,ind2 + 1,len(yourColumn)-(ind2 + 1)) subcode
FROM ( 
  SELECT yourColumn, charindex('|',yourColumn,1) ind1, 
         charindex('|',yourColumn,charindex('|',yourColumn,1)+1) ind2 
  FROM yourTable
) X

答案 1 :(得分:1)

假设您的代码总是三个字母,您可以使用一些内置函数来帮助您:

WITH Data(Sample) AS
(
    SELECT 'Pear | S01 | 10' UNION
    SELECT 'Pineapple | S01 | 9'
)
SELECT
    SUBSTRING([Sample], CHARINDEX(' | ', [Sample], 1) + 3, 3) AS Code,
    REVERSE(SUBSTRING(REVERSE([Sample]), 1, 
        CHARINDEX(' | ', REVERSE([Sample]), 1) - 1)) AS SubCode
FROM
    data