Using a declared field in stored procedures to name a table

  • does anyone know if it is possible to use a declared field to name a table?

    example

    declare @tablename as char(50)

    select @tablename = nameoftable from

      where tabledisc = 1

      select * from @tablename

    1. i would do it like this

      DECLARE @tableName AS varchar (50), @sqlCmd varchar(max)

      SELECT @tableName=nameOfTable

      FROM

        WHERE tabledisc = 1

        SELECT @sqlCmd='SELECT * FROM '+@tableName

        EXEC sp_executesql @sqlCmd

        dynamic SQL is the best choice for this sort of queries

        Here is one of the best article about it

        http://www.sommarskog.se/dynamic_sql.html

      1. Thanks! the article you referred to had all the information I needed

      Viewing 3 posts - 1 through 2 (of 2 total)

      You must be logged in to reply to this topic. Login to reply