Results 1 to 7 of 7

Thread: TSQL - help with script (MSSQL 2K)

  1. #1
    Join Date
    May 2005
    Posts
    111

    TSQL - help with script (MSSQL 2K)

    declare @foo varchar(40)
    set @foo = 'user_mstr'

    select * from @foo



    result: Must declare the table variable "@foo".


    please help!!! whenever i use the variable in a where statement i receive no errors. when as the tablename i received the above error.

  2. #2
    Join Date
    Sep 2002
    Posts
    5,938
    Try dynamic sql like:

    declare @foo varchar(40)
    declare @cmd varchar(40)
    set @foo = ''user_mstr'
    select @cmd = 'select * from ' + @foo
    exec(@cmd)

  3. #3
    Join Date
    Aug 2006
    Posts
    57
    don't use dynamic sql without reading this first:

    http://www.sommarskog.se/dynamic_sql.html

  4. #4
    Join Date
    May 2005
    Posts
    111
    rmiao, first of all thank you for responding to my post yesterday with:

    declare @foo varchar(40)
    declare @cmd varchar(40)
    set @foo = 'user_mstr'
    select @cmd = 'select * from ' + @foo
    exec(@cmd)

    however, one more thing; what if i want to add a like statement? eg.,

    select @cmd = 'select * from ' + @foo + 'where visit_no not like where visit_no not like '[0-9]%''

    the single quotes are my problem in the like statement wrapped in single quotes for the @cmd

  5. #5
    Join Date
    May 2005
    Posts
    111
    nevermind, i figured it out---thanks again for pointing in the right direction.

  6. #6
    Join Date
    May 2005
    Posts
    111
    FYI---in case you're interested:

    select @cmd = 'select * from ' + @tblname + ' where visit_no not like ''' + @zena + ''''

  7. #7
    Join Date
    Sep 2002
    Posts
    5,938
    Try this with double quotes:

    select @cmd = 'select * from ' + @foo + 'where visit_no not like where visit_no not like "[0-9]%'''

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •