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

后端 未结 10 1518
無奈伤痛
無奈伤痛 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:38

    If @locid is a list eg "33, 234" etc, then no solution here will work. However, I guess these were posted before your update with this information.

    I assume that because you said this:

    @locid is the results given by the user, for example '33, 234'

    You can not expand the variable directly so that location_in IN (33, 234). You are actually asking for location_id = '33, 234', which will fail with a CAST conversion, because of datatype precedence.

    You have to parse the list first into a table form for use in a JOIN/EXISTS construct. There are several options and Erland covers them all here: Arrays and Lists in SQL Server 2005

    0 讨论(0)
  • 2021-02-09 14:42
    WHERE CHARINDEX(LocationId, @lid) > 1
    
    0 讨论(0)
  • 2021-02-09 14:48

    You don't really need the ternary operator for this:

    SELECT top 20 application_id, [name], location_id
    FROM apps
    WHERE (@lid > 0 AND location_id IN (@lid)) OR @lid <= 0
    
    0 讨论(0)
  • 2021-02-09 14:48

    The following should do the trick for you.

    DECLARE @lid SMALLINT

    SET @lid = 0

    SELECT top 20 application_id, [name], location_id

    FROM apps

    WHERE ((@lid > 0 AND location_id = @lid)

      OR (@lid = 0 AND location_id > @lid))
    

    If @lid = 0 then it will return ALL rows. IF @lid has a particular value, only the row for that @lid value is returned.

    0 讨论(0)
提交回复
热议问题