Search code examples
sqlfunctioncoldfusioninsertioncfquery

How to call an INSERT query by name?


I've to clone a class ID #FORM.classid# several times but instead of writing the INSERT sql query each time I need it, is there any solution to just write it one time and call the query with its addClass name ? I wish I know how to code functions but I'm a newbie to CFML programming.

<cfquery name="currentClass" datasource="#dsn#">
        SELECT class_name, class_description
        FROM classes
        WHERE classid = <cfqueryparam value="#FORM.classid#" cfsqltype="cf_sql_numeric"> 
</cfquery>
<cfquery name="addClass" datasource="#dsn#">   
        INSERT INTO classes (class_name,class_description)
        VALUES ('#currentClass.class_name#', '#currentClass.class_description#')
</cfquery>
<cfquery name="getNewID" datasource="#dsn#">
        Select LAST_INSERT_ID() as classid
</cfquery>

Solution

  • Make a function to do the work for you and then call that function. This is how you could do the function if making it within ColdFusion. You could though simplify the amount of queries you are running to get to your end goal but I just wrote this via what you are already doing:

    <cffunction name="AddTheClass" access="public" returntype="numeric">
        <cfargument name="ClassID" required="true" type="numeric" />
    
        <cfscript>
            var currentClass    = "";
            var addClass        = "";
            var getNewID        = "";
    
            var myResult        = 0;
        </cfscript>
    
        <cfquery name="currentClass" datasource="#dsn#">
            SELECT class_name, class_description
            FROM classes
            WHERE classid = <cfqueryparam value="#Arguments.classid#" cfsqltype="cf_sql_numeric"> 
        </cfquery>
        <cfquery name="addClass" datasource="#dsn#">   
            INSERT INTO classes (class_name,class_description)
            VALUES ('#currentClass.class_name#', '#currentClass.class_description#')
        </cfquery>
        <cfquery name="getNewID" datasource="#dsn#">
            Select LAST_INSERT_ID() as classid
            </cfquery>
    
        <cfset myResult = getNewID.classid />
    
        <cfreturn myResult />
    </cffunction>
    
    <!--- How to call it --->
    <cfset intNewClassID    = AddTheClass(ClassID=Form.classid) />
    

    EDIT: You may need to make adjustments for your datasource variable. Kind of depends on where it comes from and hard to tell since you did not scope that variable.