Must declare the variable @myVar???????????????

  • 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.

  • It should be

    select @myVar

    instead of

    select * from @myVar

    since @myVar is not a table variable.

     

    Pat

  • 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)



    Shamless self promotion - read my blog http://sirsql.net

  • 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.

  • 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.

  • 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



    Shamless self promotion - read my blog http://sirsql.net

  • 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