Help with a sql search query using a comma delimitted parameter

后端 未结 6 889
深忆病人
深忆病人 2020-12-20 10:15

I am looking for something like this but can\'t figure out the best way to write the query:

SELECT DISTINCT CategoryID FROM tbl_Categories c INNER JOIN 
  ma         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 10:31

    -- Parameter string
    declare @ParamStr varchar(100) = '234,245,645'
    
    -- Convert param to xml
    declare @XMLStr xml = convert(xml, ''+replace(@ParamStr, ',', '')+'')
    
    -- Store param values in table variable
    declare @T table (ID int)
    insert into @T 
    select r.value('.', 'int')
    from @XMLStr.nodes('r') r(r)
    
    -- Get the number of parameters
    declare @ParamCount int = (select count(*) from @T)
    
    -- Get the categoryids
    select CategoryID
    from mappingTable
    where SubCategoryID in (select id from @T)
    group by CategoryID
    having count(CategoryID) = @ParamCount
    

提交回复
热议问题