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,但目前我无法执行它。我希望有一些想法。
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
该问题未指定数据库引擎;我从语法中假设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 |
+------+