我有一个表tbl_Country
,其中包含名为ID
和Name
的列。 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
答案 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