求一SQL语句!麻烦大家来帮帮忙!

deavey 2003-11-06 02:14:38
一个表 JH
它的结构如下

ID SET
----------------------------------
1 2,3,4,5
2 3,4,7
3 2,8
4 6,3,2

给定一个集合,譬如(2,3);
现要求查询出其字段SET与给定集合有交集的记录
请问SQL语句怎么写?
...全文
52 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
deavey 2003-11-06
  • 打赏
  • 举报
回复
是的,就是这样的,谢谢你了!
zjcxc 元老 2003-11-06
  • 打赏
  • 举报
回复
是否有任意数据在列表中都算?
我写的是全匹配,即只有给定的数据全部都有的时候才算合格.如果是任意一个在都算的话,就改函数.

--自定义函数,比较一个字符串中的数字是否在另一个字符串中
create function f_comparestr(@str1 varchar(8000),@str2 varchar(8000))
returns bit
as
begin
declare @tb1 table(st varchar(100))
declare @tb2 table(st varchar(100))
declare @i int,@re bit

select @i=charindex(',',@str1)
while @i>0
begin
insert into @tb1 values(left(@str1,@i-1))
select @str1=substring(@str1,@i+1,8000)
,@i=charindex(',',@str1)
end
if @str1<>'' insert into @tb1 values(@str1)

select @i=charindex(',',@str2)
while @i>0
begin
insert into @tb2 values(left(@str2,@i-1))
select @str2=substring(@str2,@i+1,8000)
,@i=charindex(',',@str2)
end
if @str2<>'' insert into @tb2 values(@str2)

set @re=case when exists(select 1 from @tb1 a join @tb2 b on a.st=b.st)
then 1 else 0 end
return(@re)
end
go


--利用函数实现你的要求
--创建数据测试环境
declare @tb table(id int identity(1,1),[set] varchar(100))
insert into @tb
select '2,3,4,5'
union all select '3,4,7'
union all select '2,8'
union all select '6,3,2'

--查询结果
select * from @tb
where dbo.f_comparestr([set],'2,3')=1

--删除函数
drop function f_comparestr

deavey 2003-11-06
  • 打赏
  • 举报
回复
谢谢你的回答,可是我要的结果应该是四个测试数据都是合乎要求的即两个集合的交集,是不是哪里判断有点问题了,麻烦你再忙我看看!
zjcxc 元老 2003-11-06
  • 打赏
  • 举报
回复
结果:

id set
----------- ----------
1 2,3,4,5
4 6,3,2

(所影响的行数为 2 行)
zjcxc 元老 2003-11-06
  • 打赏
  • 举报
回复
--要用函数

--自定义函数,比较一个字符串中的数字是否在另一个字符串中
create function f_comparestr(@str1 varchar(8000),@str2 varchar(8000))
returns bit
as
begin
declare @tb1 table(st varchar(100))
declare @tb2 table(st varchar(100))
declare @i int,@re bit

select @i=charindex(',',@str1)
while @i>0
begin
insert into @tb1 values(left(@str1,@i-1))
select @str1=substring(@str1,@i+1,8000)
,@i=charindex(',',@str1)
end
if @str1<>'' insert into @tb1 values(@str1)

select @i=charindex(',',@str2)
while @i>0
begin
insert into @tb2 values(left(@str2,@i-1))
select @str2=substring(@str2,@i+1,8000)
,@i=charindex(',',@str2)
end
if @str2<>'' insert into @tb2 values(@str2)

select @re= case when (select sum(1) from @tb2)-
(select sum(1) from @tb2 a inner join @tb1 b on a.st=b.st)=0
then 1 else 0 end
return(@re)
end
go


--利用函数实现你的要求
--创建数据测试环境
declare @tb table(id int identity(1,1),[set] varchar(100))
insert into @tb
select '2,3,4,5'
union all select '3,4,7'
union all select '2,8'
union all select '6,3,2'

--查询结果
select * from @tb
where dbo.f_comparestr([set],'2,3')=1

--删除函数
drop function f_comparestr

34,593

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧