How do I pass a list as a parameter in a stored procedure?

前端 未结 7 1513
暖寄归人
暖寄归人 2020-12-02 22:15

Looking to pass a list of User IDs to return a list names. I have a plan to handle the outputed names (with a COALESCE something or other) but trying to find the best way to

7条回答
  •  温柔的废话
    2020-12-02 22:48

    You can try this:

    create procedure [dbo].[get_user_names]
        @user_id_list varchar(2000), -- You can use any max length
    
        @username varchar (30) output
        as
        select last_name+', '+first_name 
        from user_mstr
        where user_id in (Select ID from dbo.SplitString( @user_id_list, ',') )
    

    And here is the user defined function for SplitString:

    Create FUNCTION [dbo].[SplitString]
    (    
          @Input NVARCHAR(MAX),
          @Character CHAR(1)
    )
    RETURNS @Output TABLE (
          Item NVARCHAR(1000)
    )
    AS
    BEGIN
          DECLARE @StartIndex INT, @EndIndex INT
    
          SET @StartIndex = 1
          IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
          BEGIN
                SET @Input = @Input + @Character
          END
    
          WHILE CHARINDEX(@Character, @Input) > 0
          BEGIN
                SET @EndIndex = CHARINDEX(@Character, @Input)
    
                INSERT INTO @Output(Item)
                SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)
    
                SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
          END
    
          RETURN
    END
    

提交回复
热议问题