我有一个列Description
,其中包含字符串值。我想在某些特殊字符上拆分为2列,以生成以下2列:
1:测试/优雅条件
2:TASK100:优雅物品
以下样本数据的预期输出应该是column1和column2
Column1
----------------
Individual/ Team Actions
Individual/ Team Actions
Task/ Environmental Conditions
Task/ Environmental Conditions
Task/ Environmental Conditions
Column2
---------
NULL
NULL
TW08: Equipment Integrity
TW01: Task Planning/ Preparation/ Manning
TW03: Work Procedures - Availability and Suitability
示例数据:
CREATE TABLE [Test]
(
[Description] [varchar](250) NULL
)
insert into [Test] values
('Individual/ Team Actions\|2018.04.11 00:01:37\|N');
insert into [Test] values
('Individual/ Team Actions\|2018.04.11 00:01:37\|N');
insert into [Test] values
('Task/ Environmental Conditions : TW08: Equipment Integrity\|2018.04.11 00:01:37\|N');
insert into [Test] values
('Task/ Environmental Conditions : TW01: Task Planning/ Preparation/ Manning\|2018.04.11 00:01:37\|N');
insert into [Test] values
('Task/ Environmental Conditions : TW03: Work Procedures - Availability and Suitability\|2018.04.11 00:01:37\|N');
我使用了以下示例查询:
declare @a varchar(300)
select @a = 'Individual/ Team Actions\|2018.04.11 00:01:37\|N'
select @a C1,
ltrim(rtrim(left(@a, charindex(':', @a)-1))) C2,
ltrim(rtrim(substring(@a,
charindex(':', @a)+1,
charindex('\', @a)-(charindex(':', @a)+1) ))) C3
但出现以下错误:
Invalid length parameter passed to the LEFT or SUBSTRING function.
答案 0 :(得分:1)
试试:
SELECT
case when charindex(' : ', description) = 0 then SUBSTRING(Description, 0, CHARINDEX('\|', Description)) else SUBSTRING(SUBSTRING(Description, 0, CHARINDEX('\|', Description)), 0, charindex(' : ', description)) end,
CASE WHEN CHARINDEX(' : ', Description) = 0 THEN NULL ELSE SUBSTRING(Description, CHARINDEX(' : ', Description) + 3, CHARINDEX('\|', Description) - CHARINDEX(' : ', Description) - 3) END
FROM Test
返回:
Individual/ Team Actions | NULL
Individual/ Team Actions | NULL
Task/ Environmental Conditions | TW08: Equipment Integrity
Task/ Environmental Conditions | TW01: Task Planning/ Preparation/ Manning
Task/ Environmental Conditions | TW03: Work Procedures - Availability and Suitability