SELECT FROM Table,表名在变量SQL中

时间:2014-06-25 15:34:17

标签: sql sql-server database sql-server-2008 sql-server-2008-r2

如何将执行结果保存到变量中?我想将计数给出的整数保存到变量

    DECLARE @count INT

    SET @sqlString = 'SELECT COUNT (DISTINCT process) FROM @tableName
        + ' WHERE process =''' + @process + '''' + 'AND stage ='
        + '''' + @varStage+ ''''

        PRINT @sqlString
    SET @count = EXEC (@sqlString)

这是我的想法,但最后一行不起作用。

1 个答案:

答案 0 :(得分:1)

EXEC doesn't return the count value, you need to select @count within the statement


 Create Table #Temp(Number int)
 DECLARE @count INT

    SET @sqlString = 'Insert Into #Temp SELECT COUNT (DISTINCT process) FROM @tableName
        + ' WHERE process =''' + @process + '''' + 'AND stage ='
        + '''' + @varStage+ ''''

  PRINT @sqlString
  EXEC (@sqlString)

  Select @count = Count(*)
  From #Temp