我有一个由 1 列组成的结果集,在本例中为 2 行,单列 [ProductDescription] 是一个 varchar 字段,其中包含 3 条信息(我没有设计它),我需要将这三条信息分成 3 个使用查询的附加字段
before
/------------------------------\
|ProductDescription |
|------------------------------|
|DB1 - DB2 - DB3 |
|DataBit1 - DataBit2 - DataBit3|
\------------------------------/
After
/---------------------------------------------------------\
|Field1 |Field2 |Field3 |ProductDescription |
|---------------------------------------------------------|
|DB1 |DB2 |DB3 |DB1 - DB2 - DB3 |
|DataBit1|DataBit2|DataBit3|DataBit1 - DataBit2 - DataBit3|
\---------------------------------------------------------/
我尝试过使用 Substring 和 charindex 的组合,但未能完全正确,字段的每个部分都可以是任意长度,因此使用硬编码偏移量不起作用。
这并不漂亮,但它有效,并且确实为您提供了您正在寻找的特定情况...如果您的 ProductDescription 中有可变数量的令牌,您可能需要创建一个存储过程来管理解析字符串时的状态,因为这很快就会变得难以管理。
create table #table(productdescription varchar(255))
go
/* Demonstrate it working in a 'pretty' case */
INSERT INTO #TABLE (ProductDescription) values ('abc - def - ghi')
go
/* Demonstrate it working in a 'ugly' case */
insert into #table (ProductDescription) values ('jklsaf -mnoa-psdfaqr')
go
SELECT RTRIM(LTRIM(SUBSTRING(ProductDescription, 0, CHARINDEX('-', ProductDescription)-1))) as Field1,
RTRIM(LTRIM(SUBSTRING(ProductDescription, CHARINDEX('-', ProductDescription)+1, (CHARINDEX('-', ProductDescription, CHARINDEX('-', ProductDescription)+1)) - (CHARINDEX('-', ProductDescription)+1)))) as Field2,
RTRIM(LTRIM(SUBSTRING(ProductDescription, CHARINDEX('-', ProductDescription, CHARINDEX('-', ProductDescription)+1)+1, LEN(ProductDescription)))) as Field3
FROM #table
go
我希望这有帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)