Help with a sql search query using a comma delimitted parameter

后端 未结 6 883
深忆病人
深忆病人 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条回答
  •  情歌与酒
    2020-12-20 10:45

    Create a split function to convert the CSV into a table value, then join the table value function to your select clause to limit the results. See http://phelabaum.com/archive/tag/tally-table/

    Quick example (requires you to create a Tally table as detailed over here http://www.sqlservercentral.com/articles/T-SQL/62867/):

    CREATE FUNCTION [dbo].[TallySplit] (@Delim CHAR(1), @String VARCHAR(8000))
        RETURNS TABLE AS 
        RETURN (
        SELECT SUBSTRING(@Delim + @String + @Delim,N+1,CHARINDEX(@Delim,@Delim + @String + @Delim,N+1)-N-1) ListValue
        FROM Tally
        WHERE N < LEN(@Delim + @String + @Delim)
        AND SUBSTRING(@Delim + @String + @Delim,N,1) = @Delim 
        )
    GO
    

    Then write your select like so:

    DECLARE @vCatIDs varchar(max)
    SET @vCatIDs = '234,245,645'
    SELECT DISTINCT CategoryID FROM tbl_Categories c 
      INNER JOIN mappingTable mp ON c.CategoryID = mp.CategoryID 
      INNER JOIN SubCategories sc ON mp.SubCategoryID = sc.SubCategoryID
      INNER JOIN dbo.TallySplit(',',@vCatIDs) ts ON ts.ListValue = sc.SubCategoryID
    

提交回复
热议问题