简体   繁体   English

DB2 SQL 按分隔符拆分记录(如果存在)

[英]DB2 SQL Split Record by Delimiter if exists

I would like to return the portion of a string BEFORE a delimiter (in this case, a hyphen).我想在分隔符(在本例中为连字符)之前返回字符串的一部分。 What I find is that DB2 is throwing an error because there's an inconsistency in the values of the column where some records have a hyphen meanwhile others do not.我发现 DB2 抛出错误,因为列的值不一致,其中一些记录有连字符,而其他记录没有。 So, I'd like to return the string before hyphen if it exists, otherwise just return the string as is.所以,如果字符串存在,我想在连字符之前返回字符串,否则就按原样返回字符串。

Example shown with COLUMN1 below:下面用 COLUMN1 显示的示例:

ID ID COLUMN1第 1 列
1 1 ASHJE-JFE ASHJE-JFE
2 2 QER-SK QER-SK
3 3 KSETK KSETK
4 4 SDJ-EJLF SDJ-EJLF

I wrote the following query to return the string prior/before '-' but, I get the following error:我编写了以下查询以在“-”之前/之前返回字符串,但是出现以下错误:

The statement was not executed because a numeric argument of a scalar function is out of range.该语句未执行,因为标量 function 的数字参数超出范围。

I believe this is because there are records where a hyphen does not exist...我相信这是因为有些记录不存在连字符......

select distinct column1, locate('-',column1), substr(column1,1, (locate('-',column1) - 1)) from db2.table
where column1 is not null
fetch first 25 rows only
with ur

Does anyone know how to accomplish something similar but return the string as is when a hyphen does not exist?有谁知道如何完成类似的事情,但在连字符不存在时按原样返回字符串? Thank you!谢谢!

You can use a CASE statement to search for the hyphen along with a LIKE operator and % wildcards.您可以使用CASE语句以及LIKE运算符和%通配符来搜索连字符。

SELECT ID, column1,
CASE WHEN column1 LIKE '%-%'
THEN substr(column1,1,locate('-',column1)-1)
ELSE column1 
END AS column2
FROM fileName
WHERE column1 IS NOT NULL
FETCH FIRST 25 ROWS ONLY

See Fiddle小提琴

Result:结果:

ID ID COLUMN1第 1 列 COLUMN2第 2 列
1 1 ASHJE-JFE ASHJE-JFE ASHJE阿什杰
2 2 QER-SK QER-SK QER质量保证
3 3 KSETK KSETK KSETK KSETK
4 4 SDJ-EJLF SDJ-EJLF SDJ SDJ

You may use the following expression:您可以使用以下表达式:

SUBSTR (COLUMN1, 1, COALESCE (NULLIF (LOCATE ('-', COLUMN1), 0) - 1, LENGTH (COLUMN1)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM