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
 General SQL Server Forums
 New to SQL Server Programming
 howt to declare a variable for a table

Author  Topic 

amirs
Constraint Violating Yak Guru

260 Posts

Posted - 2008-09-12 : 02:09:40
hi..
i just want to declare a variable for the name of the table so
that i don' have to change the table name throughout the query. I have
a table named 'host_table'. I tried the following and got the error.

declare @table1 varchar (25)
set @table1=host_table

select * from @table1

Error:
Server: Msg 137, Level 15, State 2, Line 4
Must declare the variable '@table1'.

sunil
Constraint Violating Yak Guru

282 Posts

Posted - 2008-09-12 : 02:17:07
declare @table1 Table
( lName varchar (25))

Insert into @table1
Select 'sunil' union all
select 'kumar'

select * from @table1

I am not sure what you are trying to do using set @table1=host_table. You cannot assign a table variable. Search google for "table variable Sql server"
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2008-09-12 : 02:17:10
you can't do it this way. You have to use Dynamic SQL
see
http://www.sommarskog.se/dynamic_sql.html


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2008-09-12 : 07:09:43
Yes, you can do it with dynamic sql but you should stop, consider what you are trying to do and why, then, most probably, not do it.

What, exactly, are you trying to achieve?

-------------
Charlie
Go to Top of Page
   

- Advertisement -