基于先前的答案,我将其作为解决方案提供 - 它提供了第一个和最后一个元素。如果没有找到分隔符,则最后一个元素为空。
DECLARE
@del varchar(1) = '-',
@TextIn nvarchar(20) = 'City-Of-Style'
SELECT CASE WHEN CHARINDEX(@del,@TextIn)>0 THEN SUBSTRING(@TextIn,0,CHARINDEX(@del,@TextIn,0)) ELSE @TextIn END AS firstPart,
CASE WHEN CHARINDEX(@del,@TextIn)>0 THEN SUBSTRING(@TextIn,CHARINDEX(@del,@TextIn,0)+1,LEN(@TextIn)) ELSE '' END AS secondPart
或者,如果您正在使用存储过程,则可以将结果分配给变量:
DECLARE
@del nvarchar(1) = '-',
@firstPart nvarchar(100),
@lastPart nvarchar(100),
@TextIn nvarchar(20) = 'City-Of-Style'
SELECT @firstPart = (CASE WHEN CHARINDEX(@del,@TextIn)>0 THEN SUBSTRING(@TextIn,0,CHARINDEX(@del,@TextIn,0)) ELSE @TextIn END),
@lastPart = (CASE WHEN CHARINDEX(@del,@TextIn)>0 THEN SUBSTRING(@TextIn,CHARINDEX(@del,@TextIn,0)+1,LEN(@TextIn)) ELSE '' END)
select @firstPart, @lastPart