如果未找到子字符串,则从SUBSTRING返回null

时间:2018-01-10 02:35:01

标签: sql null substring

SELECT
SUBSTRING(campaign_name,CHARINDEX(‘[’,campaign_name)+1,
(((LEN(campaign_name))-CHARINDEX(‘]’,REVERSE(campaign_name)))-
CHARINDEX(‘[’,campaign_name))) as campaign_code
FROM table

此代码目前为我提供了' ['和']'来自字段campaign_name。但是,对于campaign_name字段中的几个条目,没有' ['或者']'。在这些情况下,上面的代码返回字段中的整个字符串。相反,我想返回NULL,但目前我无法执行此操作。我会喜欢一些想法。

2 个答案:

答案 0 :(得分:0)

SELECT
CASE WHEN CHARINDEX(‘[’,campaign_name) = 0 or CHARINDEX(‘]’,campaign_name) = 0 THEN null ELSE SUBSTRING(campaign_name,CHARINDEX(‘[’,campaign_name)+1,
(((LEN(campaign_name))-CHARINDEX(‘]’,REVERSE(campaign_name)))-
CHARINDEX(‘[’,campaign_name))) END as campaign_code
FROM table

答案 1 :(得分:0)

该问题未指定数据库引擎;我从语法假设SQL Server。

SUBSTRING函数的输入之一为NULL时,它将返回NULL,因此我们可以利用NULLIF()函数来使不输入的字段无效匹配模式(即CHARINDEX == 0的模式)。

DECLARE @WORDS TABLE (
 Word VARCHAR(MAX)
);
INSERT INTO @WORDS VALUES ('abcdefghijklmnopqrstuvwxyz');
INSERT INTO @WORDS VALUES ('xyzzy');
INSERT INTO @WORDS VALUES ('la de dah');
INSERT INTO @WORDS VALUES ('redefine');
INSERT INTO @WORDS VALUES ('definitely');

DECLARE @SEARCHSTRING VARCHAR(MAX) = 'def';
SELECT 
SUBSTRING(Word,NULLIF(CHARINDEX(@SEARCHSTRING,Word),0),LEN(@SEARCHSTRING)) as Result 
FROM @WORDS
+------+
|Result|
+------+
| def  |
| NULL |
| NULL |
| def  |
| def  |
+------+