Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Problem specifying table name inside variable

Author  Topic 

azamsharp
Posting Yak Master

201 Posts

Posted - 2006-01-01 : 00:27:06
Hi,

I am writing the following T-SQL query and getting the error:
"must declare @full_name variable"

DECLARE @table_name varchar(20)
SET @table_name = 'Customers'
DECLARE @database_name varchar(20)
SET @database_name = 'Northwind..'
DECLARE @full_name varchar(20)
SET @full_name = @database_name + @table_name

Print @full_name

-- Why does it say that you must declare @full_name
SELECT * FROM @full_name

any ideas!

Mohammad Azam
www.azamsharp.net

sachinsamuel
Constraint Violating Yak Guru

383 Posts

Posted - 2006-01-01 : 02:11:52
Hi,

I have made some corrections in the query, that you have written. @fullname is declare as variable but you are referening as if its table. As the database name and table name is dynamic it can only be executed using exec() or sp_Executesql. For more information about them, please Books online.

Regards
Sachin



DECLARE @table_name varchar(20)
SET @table_name = 'Customers'
DECLARE @database_name varchar(20)
SET @database_name = 'Northwind..'
DECLARE @full_name varchar(20)
SET @full_name = @database_name + @table_name

Print @full_name

-- Why does it say that you must declare @full_name
--SELECT * FROM @full_name

declare @str varchar(100)
set @str= 'SELECT * FROM ' +@full_name

Exec ( @str)

Don't sit back because of failure. It will come back to check if you still available. -- Binu
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-01-02 : 01:56:07
Read more on Dynamice SQL
http://www.sommarskog.se/dynamic_sql.html

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -