方案一:使用內置的函數
SUBSTRING,CHARINDEX,LEN三個內置函數
理論:
SUBSTRING語法
SUBSTRING ( value_expression , start_expression , length_expression ) |
參數
- value_expression:數據庫字段
- start_expression:指定返回字符的起始位置
- length_expression:要截取的長度
返回類型
如果 expression 是其中一個受支持的字符數據類型,則返回字符數據。
CHARINDEX語法
CHARINDEX ( expression1 ,expression2 [ , start_location ] ) |
參數
- expression1:包含要查找的序列的字符表達式。 expression1 最大長度限制為 8000 個字符。
- expression2:要搜索的字符表達式。
- start_location:表示搜索起始位置的整數或 bigint 表達式。如果未指定 start_location,或者 start_location 為負數或 0,則將從 expression2 的開頭開始搜索。
返回類型
如果 expression2 的數據類型為 varchar(max)、nvarchar(max) 或 varbinary(max),則為 bigint,否則為 int。
LEN語法
LEN ( string_expression ) |
參數
- string_expression:要求值的字符串表達式。 string_expression 可以是常量、變量,也可以是字符列或二進制數據列。
返回類型
如果 expression 的數據類型為 varchar(max)、nvarchar(max) 或 varbinary(max),則為 bigint;否則為 int。
實例:
SELECT SUBSTRING(MatchMessage,CHARINDEX(',', MatchMessage)+1,LEN(MatchMessage)-CHARINDEX(',', MatchMessage)) FROM dbo.Temp_ZiXun
方案二:創建自定義函數
理論:
CREATE function [dbo].[SplitString] ( @Input nvarchar(max), --input string to be separated @Separator nvarchar(max)=',', --a string that delimit the substrings in the input string @RemoveEmptyEntries bit=1 --the return value does not include array elements that contain an empty string ) returns @TABLE table ( [Id] int identity(1,1), [Value] nvarchar(max) ) as begin declare @Index int, @Entry nvarchar(max) set @Index = charindex(@Separator,@Input) while (@Index>0) begin set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1))) if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') begin insert into @TABLE([Value]) Values(@Entry) end set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input)) set @Index = charindex(@Separator, @Input) end set @Entry=ltrim(rtrim(@Input)) if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') begin insert into @TABLE([Value]) Values(@Entry) end return end
實例:
DECLARE @imgColleciton VARCHAR(500),@BaseID INT,@value VARCHAR(5000) SELECT @imgColleciton=BaseImage FROM dbo.life_fc WHERE BaseID=44 SELECT value FROM [dbo].[SplitString](@imgColleciton,'|',0)