以动态方式为变量赋值

时间:2014-07-22 09:57:23

标签: sql-server

以下代码动态地将值分配给变量Column1到Column5

DECLARE @Column1     INT=0,
    @Column2     INT=0,
    @Column3     INT=0,
    @Column4     INT=0,
    @Column5     INT=0,
    @I           INT=0,
    @STMT_ASSIGN NVARCHAR(100)

SET @I = 1

WHILE ( @I <= 5 )
BEGIN
  SET @STMT_ASSIGN='SET @Column' + CONVERT(VARCHAR(2), @I) + '='
                   + CONVERT(VARCHAR(2), @I)

  IF @I = 1
    EXEC Sp_executesql
      @STMT_ASSIGN,
      N'@Column1 INT output',
      @Column1 = @Column1 output
  ELSE IF @I = 2
    EXEC Sp_executesql
      @STMT_ASSIGN,
      N'@Column2 INT output',
      @Column2 = @Column2 output
  ELSE IF @I = 3
    EXEC Sp_executesql
      @STMT_ASSIGN,
      N'@Column3 INT output',
      @Column3 = @Column3 output
  ELSE IF @I = 4
    EXEC Sp_executesql
      @STMT_ASSIGN,
      N'@Column4 INT output',
      @Column4 = @Column4 output
  ELSE
    EXEC Sp_executesql
      @STMT_ASSIGN,
      N'@Column5 INT output',
      @Column5 = @Column5 output

  SET @I=@I + 1
END

请建议删除if..else if ..部分,以使其成为单个sp_execute sql来分配值。因为我必须使用一个EXEC sp_executesql为50个变量分配50个值,而不是编写50个If..Else语句。

1 个答案:

答案 0 :(得分:0)

尝试以下查询:

DECLARE @Column1     INT=0,
    @Column2     INT=0,
    @Column3     INT=0,
    @Column4     INT=0,
    @Column5     INT=0,
    @I           INT=0,
    @STMT_ASSIGN NVARCHAR(100),
    @command NVARCHAR(1000)

SET @I = 1

WHILE ( @I <= 5 )
BEGIN
  SET @STMT_ASSIGN='SET @Column' + CONVERT(VARCHAR(2), @I) + '='
                   + CONVERT(VARCHAR(2), @I)

    SET @command = 'EXEC Sp_executesql
          @STMT_ASSIGN,
          N''@Column'+CAST(I AS NVARCHAR(1))+' INT output'',
          @Column'+CAST(I AS NVARCHAR(1))+' = @Column'+CAST(I AS NVARCHAR(1))+' output'

    EXEC(@command)

  SET @I=@I + 1
END