conditonal string concatenation

Discussion in 'Programming' started by Jamie18, Aug 28, 2007.

  1. #1
    what's the deal with it?

    i'm trying to create a string from a query to be used later on in an sql statement, so i need to remove null values from the list.

    heres the code i'm having problems with.

    
            <cfquery name="affectedLinks" datasource="pad">
                SELECT    *
                FROM    page_links
                WHERE    Child_ID IN (15491,622,15490)
            </cfquery>
    
            <cfoutput query="affectedLinks">
            pid    #parent_ID#<br>
            cid #child_ID#<br>
            <cfif type GT ''>type #type#<br></cfif>
            <cfif label GT ''>label #label#<br></cfif>
            <cfif Sort_Order GT ''>sort #sort_order#<br></cfif><br>
                
                <cfset tempstring = "Parent_ID = #parent_ID# AND Child_ID = #Child_ID# <cfif type GT ''>AND Type = #Type#</cfif> <cfif label GT ''>AND Label = #Label#</cfif> <cfif Sort_Order GT ''>AND Sort_Order = #Sort_Order#</cfif>">
                <cfset temp = arrayAppend(original_connections, #tempstring#)>
            </cfoutput>
    
    Code (markup):
    when i output the values based on whether or not they are GT '' it works fine.. but when i attempt to set the string based on it it doesn't..

    i.e. given this row Parent_ID = 15, Child_ID = 622, Type = null, label = somelabel, sort_order = null

    i get this output from the first part

    Parent_ID = 15
    Child_ID = 622
    label = somelabel


    but the tempstring comes out as
    'Parent_ID = 15 AND Child_ID = 622 AND Type = AND label = somelabel AND sort_order ='
    which will break my query later on..

    i've also tried this, but it throws an error
    
    <cfset tempstring = "Parent_ID = #parent_ID# AND Child_ID = #Child_ID#" <cfif type GT ''>& "AND Type = #Type#"</cfif> <cfif label GT ''>& "AND Label = #Label#"</cfif> <cfif Sort_Order GT ''>& "AND Sort_Order = #Sort_Order#"</cfif>>
    
    Code (markup):
    my next step is to create a different tempstring depending on which attributes aren't null.. i don't want to do that.. so does anybody know a way to make this work?
     
    Jamie18, Aug 28, 2007 IP
  2. Jamie18

    Jamie18 Peon

    Messages:
    201
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    i figured out a decent way to do it..


    for anyone who might want to do the same thing

    <cfset tempstring = "Parent_ID=#parent_ID# AND Child_ID=#Child_ID#"> 
    <cfif Type GT ""><cfset tempstring = tempstring & " AND Type=#Type#"></cfif> 
    <cfif Label GT ""><cfset tempstring = tempstring & " AND Label=#Label#"></cfif> 
    <cfif Sort_Order GT ""><cfset tempstring = tempstring & " AND Sort_Order=#Sort_Order#"></cfif>
    <cfset temp = arrayAppend(original_connections, #tempstring#)>
    Code (markup):
     
    Jamie18, Aug 28, 2007 IP