INFO: Object Names Cannot be Variables in TRANSACT-SQL (65466)



The information in this article applies to:

  • Microsoft SQL Server 4.2x

This article was previously published under Q65466

SUMMARY

Because object resolution occurs at compile time, TRANSACT-SQL variables (@variable) cannot be used in place of object names. For example, TRANSACT-SQL does not allow variable database names.

MORE INFORMATION

However, you can use either of the following alternatives to simulate variable table names:
  • Create a DB-Library (DB-Lib) procedure using C. The following example demonstrates this technique. Note that this example is not a complete program. See the "Microsoft SQL Server Programmer's Reference" for further information.
          ...
        
          char  table[40];
          char  *storid = "6380";
          printf ("Please Enter the table to extract: ");
          gets(table);
    
          dbfcmd(dbproc, "select * from %s ", table);
          dbfcmd(dbproc, "where stor_id = '%s' ", storid);
    
          dbsqlexec (dbproc);
    
          while (dbresults(dbproc)) != NO_MORE_RESULTS)
             dbprrow(dbproc);
          ...
    
    						
  • If you have a limited number of databases and tables, you can write a procedure to check the value of dbname and tabname and run the appropriate select statements. For example:
         create procedure getdata @dbname varchar (30),
                                  @tabname varchar (20),
                                  @dataname varchar(24)
         as
         if @dbname = "pubs"
            if @tabname = "Titles" . . .
               select * from pubs..titles
               where title_id = @dataname
            if @tabname = "titleauthor"
               select * from pubs..titleauthor
               where title_id = @dataname
         if @dbname = "tst"
            print "oops."
    
    						

Modification Type:MinorLast Reviewed:2/14/2005
Keywords:kbinfo kbProgramming KB65466