日期:2014-05-19  浏览次数:20508 次

求一条SQL语句。解决结贴
SQL语句能不能比较一个数组在不在另外一个数组里面啊
比如有个字段的值是“1,3,5,6”
我能不能看“3,6”是否在这个字段里面

我这样子试写了一下,不行

select   *   from   products   where   '8,31 '   in(属性)

------解决方案--------------------
select * from products where charindex( ',8,31, ', ', '+属性+ ', ')> 0
------解决方案--------------------

create table products(属性 varchar(20))
insert products select '1,3,5,6 '

--不连续的
select * from products where charindex( ',3, ', ', '+属性+ ', ')> 0 and charindex( ',6, ', ', '+属性+ ', ')> 0

--连续的
select * from products where charindex( ',3,5, ', ', '+属性+ ', ')> 0

drop table products
------解决方案--------------------
DECLARE @A NVARCHAR(50)
DECLARE @B NVARCHAR(50)
SET @A= '1,3,5,6 '
SET @B= '3,6 '

SELECT * FROM A
WHERE @A LIKE REPLACE( '% '+@B+ '% ', ', ', '% ')


@A 可以是你的字段名字,@B是你要搜索的字符串

------解决方案--------------------
--1=true,0=false

Create function fn_test(@a varchar(50),@b varchar(50))
returns int
AS
begin
declare @i int,@temp int
select @i=1,@temp=0
while @i> 0
begin
select @i=charindex( ', ',@a)
select @temp=@temp+case when charindex( ', '+left(@a,case when @i> 0 then @i-1 else len(@a) end)+ ', ', ', '+@b+ ', ')> 0 then 0 else 1 end
select @a=stuff(@a,1,@i, ' ')
end
if @temp> 0
set @temp=0
else
set @temp=1
return @temp

end

GO

select dbo.fn_test( '3,6 ', '1,3,4,6 ')
/*
-----------
1
*/

select dbo.fn_test( '3,6,7 ', '1,3,4,6 ')
/*
-----------
0
*/