MSSQLCity.Com - All about MS SQL
     
About Us  
SSWUG Articles  
Articles  
FAQ  
Administration  
Backup/Restore  
Connectivity  
Development  
General  
Installation  
OLAP  
Replication  
Transfer/move  
Trouble  
SQL 6.5  
Scripts  
Tips  
Test Exams  
Advertise  
Download  
History  
Search  
Traffic  
Related Links  
     
Your button logo
Add to Favorites
 
     
 


How can I use a variable for the columns/tables in the select statements?

Answer:

SQL Server can contain both static sql statements and dynamic sql statements. In comparison with static sql statements, dynamic sql statements are not completely embedded in the source code; instead, portions are stored in program variables that can be modified at run time.
So, you can use dynamic sql statements (using EXECUTE command) to execute a character string which contain a variable for the columns/tables in the select statements. Read about the EXECUTE command in SQL Server Books Online.
This is the example to make select from the table, which name was passed into the stored procedure as variable:

CREATE PROCEDURE GetRec
( @tableName  sysname )
AS
EXEC ('SELECT * from ' + @tableName)

 

 
Visit The SQL Server Worldwide User's Group for all the latest news and information about SQL Server, Oracle, DB2 and XML for developers and administrators.

(c) 1997, 2005 Bits on the Wire, Inc