简体   繁体   中英

SQL any of 1st list IN 2nd

SQL Server 2005.

I have 2 lists:

  1. ('a', 'b', 'c', 'd')

  2. ('d', 'e', 'f', 'g')

I need to make a WHERE clause with these 2 inside a dynamic SQL string, something like:

 select *
 from tbl
 where ... afewconditionshere ...
      AND anyitemfrom[('a', 'b', 'c', 'd')] is inside [('d', 'e', 'f', 'g')]

it looks kinda weird, but I get this data from a 3rd party, cannot make too big changes

the lists would always have < 20 items inside

UPDATE

a,b,c,d,e,f,g are like security things not related to the table in any way, the idea is that if you have this anyitemfrom[('a', 'b', 'c', 'd')] is inside [('d', 'e', 'f', 'g')] then you are able to view the records returned, otherwise no records should be returned

yes this condition should basically return true or false

Based on your question, it seems if you perform one IN (), then a second IN() on the filtered data set, you should get what you're looking for:

select * from
(
select * from tbl
where ... afewconditionswhere ...
and anyitemfrom in('a', 'b', 'c', 'd')
) as derived
where derived.anyitemfrom in ('d', 'e', 'f', 'g')
declare @cmd varchar(2000), @list1 varchar(100), @list2 varchar(100)

select @list1 = "('a', 'b', 'c', 'd')", @list2 = "('d', 'e', 'f', 'g')"

select @cmd =
'select * from
(
select * from tbl
where ... afewconditionswhere ...
and anyitemfrom in ' + @list1 + '
) as derived
where derived.anyitemfrom in ' + @list2


exec(@cmd)

i figured it out

i used something like :

 CREATE TABLE #t (UserName VARCHAR(50))

 DECLARE @sql VARCHAR(MAX)
 SELECT @sql = 'INSERT INTO #t SELECT ''' + REPLACE(@UserList, ',', ''' UNION SELECT ''') + ''''
 PRINT (@sql)
 EXEC (@sql)

 SELECT * FROM #t

 IF OBJECT_ID('tempdb..#t') IS NOT NULL BEGIN DROP TABLE #t END

for both lists then I was able to join them, and use the join's recordcount

 WHERE (
        SELECT COUNT(*)
          FROM ( select 'a' union all select 'b' union all select 'c' union all select 'd'
                 intersect
                 select 'd' union all select 'e' union all select 'f' union all select 'g'
               )
       ) > 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM