SQL stmt in a var

  • I want to have the following line set in a variable @S.

    select @table ='abc'

    like

    select @S = 'select @table ='abc''

    When I do the above I get an error incorrect syntax near abc

    Please help

    Thanks

  • In SQL, since we use single quotes to mark the beginning and end of character strings, we have to double up the single quotes when we intend for single quotes to be part of the SQL string. For instance:

    SET @S = 'SELECT @table = ''abc'' '

    This should set @S equal to:

    SELECT @table = 'abc'

    K. Brian Kelley

    bkelley@sqlservercentral.com

    http://qa.sqlservercentral.com/columnists/bkelley/

    Edited by - bkelley on 01/22/2002 2:22:58 PM

    K. Brian Kelley
    @kbriankelley

  • Thanks Brian! So is two single quote equal 1 single quote. Is that why we need

    SET @S = 'SELECT @table = ''abc'' '

    Thanks again

  • Also got another quick question about the same thing. If I want to print the @col which is a variable itself how can I get it?

    I have @col dynamically assigned from syscolumns as say abc. Now the next stmmt I want it to be assigned to another var so I can use it for another purpose.

    @col = 'abc'

    select @S = 'select @col_name = ''+ @col+'' '

    print @S

    When I do this all I get is

    select @col_name = '+ @col+' and not

    select @col_name = 'abc'

    Thanks

  • Thanks I got it

    select @S = 'select @col_name = '''+@col+''''

  • Yes, it looks like you've got the hang of it!

    K. Brian Kelley

    bkelley@sqlservercentral.com

    http://qa.sqlservercentral.com/columnists/bkelley/

    K. Brian Kelley
    @kbriankelley

Viewing 6 posts - 1 through 5 (of 5 total)

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