如何在一个sql语句中比较两个子查询

时间:2013-12-19 09:54:12

标签: sql sql-server select stored-procedures subquery

我有一个表tbl_Country,其中包含名为IDName的列。 Name列有多个以逗号分隔的国家/地区名称,当我传递多个国家/地区名称与Name列值进行比较时,我想要ID。我正在使用函数拆分国家/地区名称 - 示例查询如下所示:

@country varchar(50)

SELECT *
FROM   tbl_Country
WHERE  (SELECT *
        FROM   Function(@Country)) IN (SELECT *
                                       FROM   Function(Name))

tbl_country    

ID        Name
1         'IN,US,UK,SL,NZ'
2         'IN,PK,SA'
3         'CH,JP'

parameter @country ='IN,SA'

我必须得到

  ID 
   1
   2


NOTE:  The Function will split the string into a datatable

4 个答案:

答案 0 :(得分:0)

试试这个:

SELECT * 
FROM tbl_Country C 
WHERE ',' + @country + ',' LIKE '%,' + C.Name + ',%';

答案 1 :(得分:0)

试试这个

   SELECT * FROM tbl_Country C
    LEFT JOIN tbl_Country C1 ON C1.Name=C.Country

答案 2 :(得分:0)

基本上,通过在单个列中指定多个值,您违反了1st NF。因此,以下可能不是一个好方法,但提供了您正在寻找的解决方案:

  declare @country varchar(50)= 'IN,SA'
  declare @counterend int
  declare @counterstart int =1
  declare @singleCountry varchar(10)
  set @counterend = (select COUNT(*) from fnSplitStringList(@country))
  create table #temp10(
  id int
 ,name varchar(50))

 while @counterstart<= @counterend

begin

;with cte as (
select stringliteral country
, ROW_NUMBER() over (order by stringliteral) countryseq 
from fnSplitStringList(@country))
select @singleCountry = (select country FROM   cte where countryseq=@counterstart)

insert into #temp10(id, name)
select * from tbl_country t1
where not exists (select id from #temp10 t2 where t1.id=t2.id)
and name like '%' + @singleCountry +'%'

set @counterstart= @counterstart+1

end

select * from #temp10

begin drop table #temp10 end

工作原理:它分割传递的字符串并对其进行排名。然后,它遍历生成的每个Value(country)的所有记录,并将它们插入到temptable中。

答案 3 :(得分:0)

试试这个,

select a.id FROM   tbl_Country a inner join 
(SELECT country FROM   dbo.Function(@Country)) b on a.name=b.country