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.
Author |
Topic |
omicron777
Starting Member
9 Posts |
Posted - 2008-11-26 : 12:12:04
|
Here's my sql code that shows an error when executed in analyzerServer: Msg 208, Level 16, State 1, Line 3Invalid object name '@tablename'.= = =declare @tablename nvarchar(50)set @tablename = 'menov2008'select showbranch as branch, sum(wh_stock) as wh, sum(wh_stock * avg_cost) as whcostinto ME_Itemsfrom [@tablename]where substring(cardno,1,4) != 'WORK' and cardnoin (Select cardno from fg_imported.dbo.cardmaster_extension where mc in ('GR','OB'))group by showbranchorder by showbranchGO= = =Any help pls! |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-11-26 : 12:20:32
|
you need to use dynamic sql heredeclare @tablename nvarchar(50),@sql varchar(8000)set @tablename = 'menov2008'set @sql='select showbranch as branch,sum(wh_stock) as wh,sum(wh_stock * avg_cost) as whcostinto ME_Itemsfrom ['+ @tablename+']where substring(cardno,1,4) != 'WORK' and cardnoin (Select cardno from fg_imported.dbo.cardmaster_extension where mcin ('GR','OB'))group by showbranchorder by showbranch'EXEC (@sql)GO not sure why you want to send table name through a variable though |
|
|
tosscrosby
Aged Yak Warrior
676 Posts |
Posted - 2008-11-26 : 12:25:30
|
This requires dynamic SQL. Something like the following:declare @tablename nvarchar(50), @sql nvarchar(2000)set @tablename = 'menov2008'set @sql = 'select showbranch as branch,sum(wh_stock) as wh,sum(wh_stock * avg_cost) as whcostinto ME_Itemsfrom [' + @tablename + ']where substring(cardno,1,4) != ''WORK'' and cardnoin (Select cardno from fg_imported.dbo.cardmaster_extension where mcin (''GR'',''OB''))group by showbranchorder by showbranch'print @SQL - This will show you dynamic string and point to potential issuesexec sp_executesql @SQL - obviously executes itEdit - Sorry but by time I pulled it together and copy/pasted into the reply, visakh already replied. The guy is fast!!! Visakh - Do you ever sleep??Terry |
|
|
omicron777
Starting Member
9 Posts |
Posted - 2008-11-26 : 12:35:19
|
Thanks guys! Prob solved.I'm a newbie in sql server, so I'm a little mixed up. |
|
|
omicron777
Starting Member
9 Posts |
Posted - 2008-11-26 : 12:39:18
|
By the way, I'm using C# and throwing the tablename variable to sp. |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2008-11-27 : 03:13:50
|
www.sommarskog.se/dynamic_sql.htmlMadhivananFailing to plan is Planning to fail |
|
|
|
|
|
|
|