简体   繁体   English

SQL第一个列表中的第二个

[英]SQL any of 1st list IN 2nd

SQL Server 2005. SQL Server 2005。

I have 2 lists: 我有2个清单:

  1. ('a', 'b', 'c', 'd') ('A B C D')

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

I need to make a WHERE clause with these 2 inside a dynamic SQL string, something like: 我需要在动态SQL字符串中用这2创建一个WHERE子句,例如:

 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 列表中始终包含<20个项目

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 a,b,c,d,e,f,g就像安全性,与表完全无关,其思想是,如果您有此anyitemfrom [('a','b','c',' d')]位于[('d','e','f','g')]内,则您可以查看返回的记录,否则不应该返回任何记录

yes this condition should basically return true or false 是,此条件基本上应该返回true或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: 根据您的问题,似乎如果您对过滤后的数据集执行一个IN(),然后执行第二个IN(),则应该获得所需的内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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