How do I use a comma separated list of values as a filter in T-SQL?

后端 未结 10 1674
無奈伤痛
無奈伤痛 2021-02-09 14:03

I have a basic SQL query, starting with:

SELECT top 20 application_id, [name], location_id FROM apps

Now, I would like to finish it so that it

10条回答
  •  天命终不由人
    2021-02-09 14:23

    See this entry in my blog:

    • IN with a comma separated list: SQL Server

    If your @lid is a comma-delimited list of integers, use this:

    WITH    cd AS
            (
            SELECT  1 AS first, CHARINDEX(',', @lid, 1) AS next
            UNION ALL
            SELECT  next + 1, CHARINDEX(',', @lid, next + 1)
            FROM    cd
            WHERE   next > 0
            ),
            lid AS
            (
            SELECT  CAST(SUBSTRING(@lid, first, CASE next WHEN 0 THEN LEN(@lid) + 1 ELSE next END - first)AS INT) AS id
            FROM    cd
            )
    SELECT  d.*
    FROM    (
            SELECT  DISTINCT id
            FROM    lid
            ) l
    JOIN    apps a
    ON      a.location_id = l.id
            AND @lid <> '0'
    UNION ALL
    SELECT  *
    FROM    apps a
    WHERE   @lid = '0'
    

    This is much more efficient than using OR constructs.

提交回复
热议问题