SQL 截取成对符号间 且包含指定关键字的内容

截取两个“|”之间 包含 @key 关键字的 内容,用于字符串的分段截取

 /* 
 截取两个‘|’内,并且包含关键字@key的字符串
 */
Create function [dbo].[getStrByKey](@v nvarchar(200),@key nvarchar(100))
returns nvarchar(200)
as
begin
 
 declare @re nvarchar(200)
 set @re=''
 
--起始位置
 declare @bg int 
 set @bg=0
--结束位置
 declare @ed int 
 set @ed=0
	
 while(@v!='')
 begin 
	--第一个|的位置
	select @bg=patindex('%|%',@v)
	--第二个|的位置
	select @ed=patindex('%|%',SUBSTRING(@v,@bg+1,LEN(@v)))
	if @ed=0 or @bg=0
	begin 
		return ''
	end
	--@bg和@ed位置中间的字符串内容
	set @re=substring (@v,@bg,@ed)

	--判断是否包含@key
	if charindex(@key,@re)>0
		begin
			set @v=''
		end
	else 
		begin

			--继续从上面截取位置后的字符串开始查询
			set @v=SUBSTRING(@v,@bg+@ed,len(@v))		
			set @re=''	
		end
 end
 
 return @re
end

  

原文地址:https://www.cnblogs.com/vnii/p/2113699.html