June 16, 2004 at 11:03 am
Hi everyone,
I'm trying to execute the following T-SQL Statement but it's not working. Could anyone of you please let me know what's wrong with my code.
declare @myVar varchar(40)
set @myVar='HeaderTransLog'
select * from @myVar
thanx
Muneeb.
June 16, 2004 at 11:13 am
It should be
select @myVar
instead of
select * from @myVar
since @myVar is not a table variable.
Pat
June 16, 2004 at 11:17 am
It's thinking that the @myvar is a table variable in the select statement and so is looking to pull data from it. Use the variable to create a dynamic query and execute it....
declare @myVar varchar(40)
declare @sql varchar(1000)
set @myVar='HeaderTransLog'
set @sql = 'select * from ' + @myVar
exec (@sql)
June 16, 2004 at 11:17 am
Thanx Pat for your reply, but I need to use the variable in the FROM clause of the SELECT statement.
Is there a way I can use the variable in the FROM clause of the SELECT variable?
I'm trying to build a dynamic SQL Statment and passing the table name in the FROM Clause.
Thanx.
Muneeb.
June 16, 2004 at 11:27 am
Thanx Nicholas,
It worked...one more question.....is there a way that I can use the EXEC statement to return a value in a variable...
e.g..
declare @mycount int
set @mycount=exec('select count(*) from HeaderTransLog')
Thanx
Muneeb.
June 16, 2004 at 11:36 am
set nocount on
declare @myVar varchar(40)
declare @sql varchar(1000)
declare @numrows int
declare @mycount int
create table #thecount (countrows int)
set @myVar='HeaderTransLog'
set @sql = 'insert into #thecount select count(*) from ' + @myVar
exec (@sql)
select @numrows = countrows from #thecount
drop table #thecount
print @numrows
June 16, 2004 at 10:00 pm
Look up sp_executeSQL in Books Online.
--------------------
Colt 45 - the original point and click interface
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply