首页 > 数据库技术 > 详细

sql 字段分割函数 + 查询

时间:2020-01-20 18:01:18      阅读:219      评论:0      收藏:0      [点我收藏+]

结果:

用于解决  这种 字段的查询 

技术分享图片

 

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.查询   =>自己替换表

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
)

sql 字段分割函数 + 查询

原文:https://www.cnblogs.com/ykl123/p/12218496.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!