Stored procedure with variable number of parameters

后端 未结 6 1989
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 06:48

I have stored procedure where I have to pass parameters, But the problem is I am not sure how many parameters is going to come it can be 1, in next run it can be 5.

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 07:37

    Here is a code snippet that splits a string based on , as delimiter. You can even parametrize the comma. It's useful on systems that don't have the String_split function yet:

      DECLARE @startindex INT
      DECLARE @commaindex INT
      DECLARE @paramAsString VARCHAR(MAX) -- this represents the input param
      DECLARE @param VARCHAR (1024)
      DECLARE @paramsTable TABLE(param VARCHAR(1024) NOT NULL) -- the splitted params come here
    
      SET @startindex = 1
      WHILE @startindex < LEN(@paramAsString)
      BEGIN
        SET @commaindex = CHARINDEX(',', @paramAsString, @startindex)
    
        IF @commaindex = 0
        BEGIN
          SET @param = SUBSTRING(@paramAsString, @startindex, LEN(@paramAsString))
          SET @startindex = LEN(@settlementEntities)
        END
        ELSE
        BEGIN
          SET @param = SUBSTRING(@paramAsString, @startindex, (@commaindex - @startindex))
          SET @startindex = @commaindex + 1
        END
        IF @se IS NOT NULL AND 0 < LEN(RTRIM(LTRIM(@param)))
        BEGIN
          SET @param = RTRIM(LTRIM(@param))
          INSERT INTO @paramsTable (param) VALUES (@param)
        END
      END
    

提交回复
热议问题