多选项查询,适用于爱好等的搜索,有时何必行转列

本文介绍了一种使用SQL自定义函数split处理字符串的方法,并演示了如何通过子查询筛选特定条件的数据记录。通过实例展示了复杂SQL语句的构建过程。

create table #t(
 ids int identity,
 name varchar(100)
)

insert into #t(name)
select '1,2,3'
union all
select '4,2,3'
union all
select '5,2,3'
union all
select '6,2,3'
union all
select '1,4,3'
union all
select '1,5,3'
union all
select '1,6,3'
union all
select '1,2,4'
union all
select '1,2,5'
union all
select '1,2,6'
union all
select '7,8,9'
union all
select '1,8,9'
union all
select '2,8,9'
union all
select '3,8,9'
union all
select '4,8,9'
union all
select '5,8,9'
union all
select '6,8,9'
union all
select '5,6,9'
union all
select '5,7,9'
union all
select '5,3,9'
union all
select '5,0,9'


select * from #t where exists(
 select * from dbo.split(#t.name,',') as n
 inner join (select * from dbo.split('5,9',',')) as m
 on n.f1=m.f1
)

结果

同理:

select * from #t where exists(
 select * from dbo.split(#t.name,',')
 where f1 in (5,9)
)

你看懂了吗?

付:split 函数

ALTER function [dbo].[split]
(
@SourceSql varchar(8000),
@StrSeprate varchar(10)
)
returns @temp table(F1 varchar(100))
as
begin
    declare @i int
    set @SourceSql = rtrim(ltrim(@SourceSql))
    set @i = charindex(@StrSeprate,@SourceSql)
    while @i >= 1
    begin
        if len(left(@SourceSql,@i-1))>0
        begin
            insert @temp values(left(@SourceSql,@i-1))
        end
        set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
        set @i=charindex(@StrSeprate,@SourceSql)
    end
    if @SourceSql <> ''
        insert @temp values(@SourceSql)
    return
end
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值