Pass string into SQL WHERE IN

独自空忆成欢 提交于 2019-12-04 08:10:55

This is a pretty common problem -- not sure why TSQL hasn't dealt with it yet. Anyway, the solution I've found works best for me is to convert the variable to a table, and then you can use IN() on it just fine.

Starting with the function:

CREATE Function [dbo].[ParseStringList]  (@StringArray nvarchar(max) )  
Returns @tbl_string Table  (ParsedString nvarchar(max))  As  

BEGIN 

DECLARE @end Int,
        @start Int

SET @stringArray =  @StringArray + ',' 
SET @start=1
SET @end=1

WHILE @end<Len(@StringArray)
    BEGIN
        SET @end = CharIndex(',', @StringArray, @end)
        INSERT INTO @tbl_string 
            SELECT
                Substring(@StringArray, @start, @end-@start)

        SET @start=@end+1
        SET @end = @end+1
    END

RETURN
END

And then to use the function...

SELECT * 
FROM table
WHERE SomeFieldValue In (Select ParsedString From dbo.ParseStringList(@Types))

It's because you need to have a set of values separated by commas. Like

WHERE
T.TYPE_ID IN ('46', '45', '44');

Are you usign SQL Server or Oracle, MySQL?

If you have a string composed of your multiple values such as

T.TYPE_ID IN ('46,45,44');

You might need a function that will explode your string usign a delimiter (split or whatever it is called depending on you DBMS)

The following Select working fine for me:

 SELECT M.REG_NO, T.TYPE_ID 
        FROM MAIN AS M 
            INNER JOIN CLASSIFICATION AS C 
                ON M.REG_NO = C.REG_NO
            INNER JOIN TYPE AS T 
                ON T.TYPE_ID = C.TYPE_ID
        WHERE (','+@Types+',') LIKE '%,' +T.TYPE_ID+ ',%'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!