简体   繁体   中英

SELECT FROM Table where the table name is in a variable SQL

How do I save the result of my exeuction into a variable? I want to save the integer given by the count into a variable

    DECLARE @count INT

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

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

This is my idea, but the last line does not work.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM