我有一个列,其中包含 aaa | bbb | ccc 格式的数据,并且需要分别从数据中提取aaa,bbb和ccc。
我尝试过
SELECT
SUBSTRING(Column1, 0, CHARINDEX('|', Column1)) AS [First],
SUBSTRING(Column1, CHARINDEX('|', Column1) + 1, LEN(Column1)) AS [Second]
FROM
Table1
输出:
aaa [FIRST],bbb|ccc [Second]
但是我需要aaa [FIRST],bbb [Second],ccc [Third]
答案 0 :(得分:1)
如果您使用完全相同的格式(三遍)以|
分隔的字符串,则可以PARSENAME():
select col1, parsename(cols, 3) fisrt, parsename(cols, 2) second, parsename(cols, 1) third
from table1 t1 cross apply
( values (replace(col1, '|', '.'))
) t2 (cols);
答案 1 :(得分:0)
我一直这样做,对我来说效果很好:
DECLARE @delimString VARCHAR(255) = 'aaa|bbb|ccc';
DECLARE @xml XML = '<val>' + REPLACE( @delimString, '|', '</val><val>' ) + '</val>'
SELECT
x.f.value( '.', 'VARCHAR(50)' ) AS val
FROM @xml.nodes( '//val' ) x( f );
返回
+-----+
| val |
+-----+
| aaa |
| bbb |
| ccc |
+-----+
如果您正在寻找柱状收益,并且知道自己总是仅可以解析三个值,那么您可能可以摆脱下面的示例。您可以在SSMS中运行它。
DECLARE @table TABLE ( [value] VARCHAR(255) );
INSERT INTO @table ( [value] ) VALUES
( 'aaa|bbb|ccc' )
, ( '0A-PRDS|JQLM-1|1967' )
, ( 'J1658|G-1|2003' );
SELECT
[value]
, SUBSTRING( [value], 0, CHARINDEX( '|', [value] ) ) AS Column1
, SUBSTRING(
[value]
, ( CHARINDEX( '|', [value]) + 1 ) -- starting position of column 2.
, CHARINDEX( '|', [value], ( CHARINDEX( '|', [value] ) + 1 ) ) - ( CHARINDEX( '|', [value]) + 1 ) -- length of column two is the number of characters between the two delimiters.
) AS Column2
, SUBSTRING(
[value]
, CHARINDEX( '|', [value], ( CHARINDEX( '|', [value] ) + 1 ) ) + 1
, LEN( [value] )
) AS Column3
FROM @table;
返回
+---------------------+---------+---------+---------+
| value | Column1 | Column2 | Column3 |
+---------------------+---------+---------+---------+
| aaa|bbb|ccc | aaa | bbb | ccc |
| 0A-PRDS|JQLM-1|1967 | 0A-PRDS | JQLM-1 | 1967 |
| J1658|G-1|2003 | J1658 | G-1 | 2003 |
+---------------------+---------+---------+---------+
答案 2 :(得分:0)
您可以按照以下方式尝试使用函数SELECT tab1.*
from Table1 as tab1
case
when tab1.name='facebook' then left join Table2 on {condition}
when tab1.name='twitter' then left join Table3 on {condition}
,charindex
和SUBSTRING
REVERSE
答案 3 :(得分:0)
由于拆分功能在您的SQL Server版本中不可用,因此可以使用公用表表达式(CTE)拆分列中的值
WITH CTE(userString,startIndex,EndIndex)
AS
(
SELECT Column1,1,CHARINDEX('|',Column1)
FROM Table1
UNION ALL
SELECT Column1, EndIndex+1,CHARINDEX('|',Column1,EndIndex+1)
FROM CTE
WHERE EndIndex !=0
)
SELECT SUBSTRING(userString,
startIndex,
CASE WHEN EndIndex > 0
THEN EndIndex - startIndex ELSE LEN(Column1) END)
as splitVALUES
FROM CTE