SQL use comma-separated values with IN clause

前端 未结 9 1723
终归单人心
终归单人心 2020-12-19 08:49

I am developing an ASP.NET application and passing a string value like \"1,2,3,4\" into a procedure to select those values which are IN (1,2,3,4) but its saying \"Conversion

相关标签:
9条回答
  • 2020-12-19 09:25

    First create function -

    Just run this code

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE FUNCTION [dbo].[CSVToTable] (@InStr VARCHAR(MAX))
    RETURNS @TempTab TABLE
       (id int not null)
    AS
    BEGIN
        ;-- Ensure input ends with comma
        SET @InStr = REPLACE(@InStr + ',', ',,', ',')
        DECLARE @SP INT
    DECLARE @VALUE VARCHAR(1000)
    WHILE PATINDEX('%,%', @INSTR ) <> 0 
    BEGIN
       SELECT  @SP = PATINDEX('%,%',@INSTR)
       SELECT  @VALUE = LEFT(@INSTR , @SP - 1)
       SELECT  @INSTR = STUFF(@INSTR, 1, @SP, '')
       INSERT INTO @TempTab(id) VALUES (@VALUE)
    END
        RETURN
    END
    GO
    

    Then -

    Use function in bracket with select statment -

    DECLARE @LIST VARCHAR(200)
    SET @LIST = '1,3'
    SELECT Id, Descr FROM CSVDemo WHERE Id IN (SELECT * FROM dbo.CSVToTable(@LIST))
    
    0 讨论(0)
  • 2020-12-19 09:27

    Here is a workaround I found to do what you are trying to achieve

    CREATE Procedure [dbo].[sp_getUserRoles](
       @pGroupIDs varchar(50)
        )
         As
        BEGIN
            SELECT * FROM CheckList_Groups Where (',' + @pGroupIDs +',' LIKE '%,' + CONVERT(VARCHAR, id) + ',%')
       End
    

    This gets your comma delimited list and compares it to the id's(which are represented like so ',1,', ',2,' etc) in the table using LIKE

    0 讨论(0)
  • 2020-12-19 09:27

    It is not possible to put those values (the comma separated string) in a parameter-value.

    What you'll have to do, is to create the SQL Statement in your stored procedure dynamically, by string concatenation. You'll have to execute it with the sp_executesql stored procedure then.

     CREATE PROCEDURE [dbo].[getUserRoles]( @groupIds NVARCHAR(50) ) 
     AS BEGIN   
        DECLARE @statement NVARCHAR(255)
    
        SELECT @statement = N'SELECT * FROM CheckList_Groups Where id in ( ' + @pGroupIDs + N')'    
    
        execute sp_executesql @statement 
     END
    

    Also, not that I named the SP getUserRoles instead of sp_getUserRoles. The reason is very simple: when you execute a stored procedure whose name starts with sp_, then SQL Server will first query the master database to find that stored procedure, which causes a performance hit offcourse.

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