sql 字段分割函数 + 查询

结果:

用于解决  这种 字段的查询 

1.先创建分割函数 => 复制到数据库直接执行

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
by kudychen 2011-9-28
*/
CREATE function [dbo].[SplitNum]
(
@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

2.查询   =>自己替换表

扫描二维码关注公众号,回复: 8733590 查看本文章

SplitNum=>函数,

Value=> 要查询的值

----------------------------------

select * from 表 where id
in
(
select distinct ad.adid from (select a.id adid,recrid.Id,recrid.Value from 表 a outer apply SplitNum(a.expirationdate,',',2) recrid ) ad where ad.Value=15
)

猜你喜欢

转载自www.cnblogs.com/ykl123/p/12218496.html