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

前端 未结 6 1307
说谎
说谎 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
    

提交回复
热议问题