Problem SELECTing declared variables

  • Hi Folks,

    I have a table called base1005 (word 'base' and  mmyy) in my database and i am trying to count the number of records in each file (as well as some other commands) from this file.  I want to call the file name through a variable however the SELECT part of the following program states that the variable @churn1 has not been declared. Does anyone know why this is???

    declare @churn varchar(20),@churn1 varchar(20)

    set @churn='1005'

    set @churn1='base'+@churn

    print @churn1

    select * from @churn1

    BTW - the PRINT statement works but the SELECT part doesn't!

    Cheers

  • You have to use dynamic sql for this....

    declare @churn varchar(20),@churn1 varchar(20)
    set @churn='1005'
    set @churn1='base'+@churn
    print @churn1
    --select * from @churn1 - INCORRECT
    exec('select * from ' + @churn1)
    

    read this wonderful article on dynamic sql!







    **ASCII stupid question, get a stupid ANSI !!!**

  • Thank you very very very much!!

    I just thought I would reply to say thanks before I dive into the scary topic of Dynamic SQL.

  • Do I miss something here Friday.

    Wouldn't this work!

    declare @churn varchar(20),@churn1 varchar(20)

    set @churn='1005'

    set @churn1='base'+@churn

    print @churn1

    --select * from @churn1

    select  @churn1 churn1

     

    Regards,
    gova

  • I would still need a dynamic query to SELECT * from the base1005 table though wouldn't I?

    I am a bit confused.

  • My Mistake.

    Friday Morning. I didn't realise  @churn1 holds a table name. Sushila is right. Dynamic SQL is the answer.

    Print statement works and select didn't misled me.

    Regards,
    gova

  • No probs.

    Thanks for your help anyway.

    Hope friday afternoon is a bit better.

  • Govinn, I think you might have misread the question.  The variable stores the table name

  • Whoops - seems you and I are often on here replying to questions at the same time Govinn - seems you corrected your misread while I was typing! 

    Apologies

Viewing 9 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic. Login to reply