只需使用CASE
语句来确定是否|
存在。如果它不存在CHARINDEX
将返回:0
DECLARE @val VARCHAR(15) = 'SH1684|32I5'
-- show the value
SELECT @val
-- returns the section before the pipe
SELECT CASE WHEN CHARINDEX('|', @val) > 0
THEN SUBSTRING('SH1684|32I5', 1,
CHARINDEX('|', 'SH1684|32I5') - 1)
ELSE @val
END AS ID
-- set value without pipe
SET @val = 'SH168432I5'
-- same query returns entire value as there is no pipe
SELECT CASE WHEN CHARINDEX('|', @val) > 0
THEN SUBSTRING('SH1684|32I5', 1,
CHARINDEX('|', 'SH1684|32I5') - 1)
ELSE @val
END AS ID
因此,|
如果它存在,它将返回之前的部分,否则它将返回整个值。