如何从 A 列中像这样从查询 sql 中获取代码和子代码
格式 :
[very long name | code | subcode]
例如
[Pear | S01 | 10]
[Pineapple | S01 | 9]
PS:没有方括号,但管道分隔符是真实的
尝试这个; 演示 - 用表格更新
--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
假设您的代码始终是三个字母,您可以使用一些内置函数来帮助您:
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