Concatenating data in a variable

  • I'm trying to set a variable equal to a string based on a combination of criteria. For example:

    If criteria 1 evaluates to TRUE, set @Variable = 'Text for 1'

    If criteria 2 evaluates to TRUE, set @Variable = 'Text for 2'

    If criteria 1 AND 2 are TRUE, set @Variable = 'Text for 1 Text for 2'

    My code is something like this:

    if not exists (select * from table where id = 1)

      begin

        set @variable = 'Text for 1'

    end

    if not exists (select * from table where id = 2)

      begin

        set @variable = @variable + ' Text for 2'

    etc...

    I can only get it to concatenate if the 1st criteria evaluates to true. What am I doing wrong?

    Thanks in advance

  • You might want to check for NULL in @variable before you concatenate it with anything.  I think NULL concatenated with anything yields NULL.


    And then again, I might be wrong ...
    David Webb

  • Maybe try initialising @variable before the conditions to get rid of possible NULL issues.  Eg

    set @variable = ''

    if not exists (select * from table where id = 1)

      begin

        set @variable = 'Text for 1'

    end

    if not exists (select * from table where id = 2)

      begin

        set @variable = @variable + ' Text for 2'

    etc...

    The absence of evidence is not evidence of absence
    - Martin Rees
    The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
    - Phil Parkin

  • If we could see the relevant portions of the actual code we might be able to spot the problem.

    ron

  • Phil, that solved my problem. Thanks to everybody who helped me out

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

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