I usually create update statements like this. But I know there is a better way. How can I approve upon this? *Note the sample below is pseudo demo, may not run.
<cffunction name="updateEmp" returntype="void">
<cfargument name="empId" required="yes" hint="empId">
<cfargument name="firstName" required="yes" hint="firstName">
<cfargument name="lastName" required="yes" hint="lastName">
<!--- Get emp details in db --->
<cfquery datasource="#ds#" name="getEmployee">
SELECT *
FROM Employee
WHERE emp_id = <cfqueryparam
value="#arguments.empId#"
CFSQLType="CF_SQL_INTEGER">
</cfquery>
<!--- If employee is in db or if emp db details are different --->
<cfif getEmployee.recordCount eq 1
and getEmployee.firstName neq trim(arguments.firstName)
or getEmployee.lastName neq trim(arguments.lastName)>
<cfquery name="UpdateExistingEmployee" datasource="#ds#">
UPDATE Employee
SET 1 = 1
<cfif getEmployee.firstName neq trim(arguments.firstName)>
,firstName = <cfqueryparam
value="#arguments.firstName#"
CFSQLType="CF_SQL_VARCHAR" >
</cfif>
<cfif getEmployee.lastName neq trim(arguments.lastName)>
,lastName = <cfqueryparam
value="#arguments.lastName#"
CFSQLType="CF_SQL_VARCHAR" >
</cfif>
WHERE emp_id=<cfqueryparam
value="#emp_id#"
CFSQLType="CF_SQL_INTEGER">
</cfquery>
</cfif>
<!--- maybe return success? --->
</cffunction>
Edited:
<cffunction name="updateEmp" returntype="void">
<cfargument name="empId" required="yes" hint="empId">
<cfargument name="firstName" required="yes" hint="firstName">
<cfargument name="lastName" required="yes" hint="lastName">
<cfquery name="UpdateExistingEmployee" datasource="#ds#">
UPDATE Employee
SET firstName = <cfqueryparam
value="#arguments.firstName#"
CFSQLType="CF_SQL_VARCHAR" >
,lastName = <cfqueryparam
value="#arguments.lastName#"
CFSQLType="CF_SQL_VARCHAR" >
WHERE emp_id=<cfqueryparam
value="#emp_id#"
CFSQLType="CF_SQL_INTEGER">
</cfquery>
<!--- maybe return success? --->
</cffunction>
Not sure what you are trying to improve. If you just want to write less code you might just do an update:
The check for an existing record is pretty much superfluous since the where clause will prevent any action if no emp_id matches, and why bother checking if the names match? If they do, then you just updated them to be the same, if they don’t you’re going to update them anyway. There’s no logical reason to be doing all that checking.