How can I check whether a number is contained in comma separated list stored in a varchar column?

前端 未结 6 1304
说谎
说谎 2021-01-11 12:48

I have a table with a varchar column categoryIds. It contains some IDs separated by commas, for example:

id       categoryIds
-----         


        
相关标签:
6条回答
  • 2021-01-11 13:11

    You should really redesign this table to split out those values from being comma separated to being in individual rows. However, if this is not possible, you are stuck with doing string comparison instead:

    DECLARE @id INT = 3
    DECLARE @stringId VARCHAR(50) = CAST(@id AS VARCHAR(50))
    
    SELECT * 
    FROM MyTable 
    WHERE categoryIds = @stringId -- When there is only 1 id in the table
    OR categoryIds LIKE @stringId + ',%' -- When the id is the first one
    OR categoryIds LIKE '%,' + @stringId + ',%' -- When the id is in the middle
    OR categoryIds LIKE '%,' + @stringId -- When the id is at the end
    
    0 讨论(0)
  • 2021-01-11 13:11

    You could use dynamic SQL like this:

    DECLARE     @categoryIds    nvarchar(50) = '1, 2, 3, 4, 5'
    
    EXEC        ('SELECT      *
                  FROM        myTable
                  WHERE       categoryId IN (' + @categoryIds + ')')
    
    0 讨论(0)
  • 2021-01-11 13:14

    use FIND_IN_SET() mysql function

    Syntax

    SELECT * FROM <table name> as a WHERE FIND_IN_SET(value to search in string,comma separated string);
    

    Example

    SELECT * FROM <table name> as a WHERE FIND_IN_SET(5,"1,2,3,4,5,6");
    
    0 讨论(0)
  • 2021-01-11 13:18

    Not sure if this would be faster or slower than DavidG's suggestion, but in order to get the same matches with only one check, you can do:

    DECLARE @categoryId INT
    SET @categoryId = 3
    
    SELECT *
    FROM myTable
    WHERE CHARINDEX(',' + CAST(@categoryId AS VARCHAR(MAX)) + ',', ',' + categoryIds + ',') > 0
    
    0 讨论(0)
  • 2021-01-11 13:29
    SELECT * 
    FROM myTable 
    WHERE (',' + RTRIM(categoryIds) + ',') LIKE '%,' + @stringId + ',%'
    

    Here @stringId is your text to be searched. In this way you can avoid unnecessary multiple where conditions

    Kind Regards, Raghu.M.

    0 讨论(0)
  • 2021-01-11 13:29

    SELECT * FROM user_master WHERE (user_tags regexp '[[:<:]]10[[:>:]]' or user_tags regexp '[[:<:]]11[[:>:]]')

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