select clause into string variable

  • greetings

    given the following code, I'm able to store a fetched field into a variable, for later use:

    use northwind

    declare @Foo varchar(8000)

    set @Foo = (select categoryname from categories where categoryid=1)

    print @Foo

    Now imagine I want to store, on a similar way, a different value, which has spaces in it... like in:

    declare @Foo varchar(8000)

    set @Foo = (select description from categories where categoryid=1)

    print @Foo

    (I get an error when I try this. I haven't been able to find out the way to quote the value)

    Following the same line of thought, is there any way to do a "select *" into a varchar variable? or in a more politically correct way:

    select 'val = ' <plus> categoryname <plus> ' desc = ' <plus> description from categories where categoryid=1

    ??

    <plus> are 'plus' signs. something is taking them off the text...

    thanks in advance

  • try something like:

    declare @Foo varchar(8000)

    select @Foo=cast(description as varchar(8000)) from categories where categoryid=1

    print @Foo

    Gregory Larsen, DBA

    If you looking for SQL Server Examples check out my website at http://www.geocities.com/sqlserverexamples

    Gregory A. Larsen, MVP

  • your select statement re-written as follows should work :

    select 'val = ' + categoryname + ' desc = ' + Convert(Varchar(100),description) from categories where categoryid=1

    Since description is of type ntext you need to convert it to the proper datatype...

    To put the results into a variable :

    Declare @Foo varchar(8000)

    SELECT @Foo = 'val = ' + categoryname + ' desc = ' + Convert(Varchar(100),description) from categories where categoryid=1

    Print @Foo

    p.s : The 'plus' signs might not appear in the "Preview" option during post but they will appear in the message after it has been posted...I faced the same problem... 🙂

    Edited by - winash on 06/04/2003 11:09:24 AM

Viewing 3 posts - 1 through 2 (of 2 total)

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