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.查詢   =>自己替換表

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
)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM