SQL : in clause in stored procedure:how to pass values

前端 未结 8 1925
小蘑菇
小蘑菇 2020-11-27 18:12

I want to write a SQL Server 2005 stored procedure which will select and return the user records from the user table for some userids which are passed to the stored procedur

8条回答
  •  被撕碎了的回忆
    2020-11-27 18:31

    Assuming T-SQL, you can use this nice function (that returns a table).

    DROP FUNCTION sp_ConvertStringToTable
    GO
    CREATE FUNCTION sp_ConvertStringToTable(@list ntext)
          RETURNS @tbl TABLE (Position INT IDENTITY(1, 1) NOT NULL,
                              Value INT NOT NULL) AS
       BEGIN
          DECLARE @pos      int,
                  @textpos  int,
                  @chunklen smallint,
                  @str      nvarchar(4000),
                  @tmpstr   nvarchar(4000),
                  @leftover nvarchar(4000)
    
          SET @textpos = 1
          SET @leftover = ''
          WHILE @textpos <= datalength(@list) / 2
          BEGIN
             SET @chunklen = 4000 - datalength(@leftover) / 2
             SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))
             SET @textpos = @textpos + @chunklen
    
             SET @pos = charindex(' ', @tmpstr)
             WHILE @pos > 0
             BEGIN
                SET @str = substring(@tmpstr, 1, @pos - 1)
                INSERT @tbl (Value) VALUES(convert(int, @str))
                SET @tmpstr = ltrim(substring(@tmpstr, @pos + 1, len(@tmpstr)))
                SET @pos = charindex(' ', @tmpstr)
             END
    
             SET @leftover = @tmpstr
          END
    
          IF ltrim(rtrim(@leftover)) <> ''
             INSERT @tbl (Value) VALUES(convert(int, @leftover))
    
          RETURN
       END   
    GO
    

    In this way:

    SELECT * FROM Users 
    WHERE userid IN 
    ( SELECT Value FROM sp_ConvertStringToTable('1 2 3') )
    

    You can change the stored function to work with comma separated strings instead of space separated ones.

    If you don't want / can't use a stored function you can include the code of it inside the stored procedure where needed.

    EDIT: this is incredibly more performant than the string concatenation.

提交回复
热议问题