Link to home
Start Free TrialLog in
Avatar of AlexPonnath
AlexPonnathFlag for United States of America

asked on

whow to capture SQL errors in Coldfusion

I have a bunch of queries which insert data into my SQL server and sometimes I get a duplicate record which
throws an error like this

Error Executing Database Query.[Macromedia][SQLServer JDBC Driver][SQLServer]Violation of PRIMARY KEY constraint 'PK_tbl_CNR_D'. Cannot insert duplicate key in object 'dbo.tbl_CNR_D'. The duplicate key value is (C2491035056, 01, 1428310095, ). The specific sequence of files included or processed is: C:\inetpub\wwwroot\parse.cfm, line: 452

how can I capture this in my code and act accordingly ?

I want to avoid to have to fire of a query to see if recordcount GT 0 to avoid this
ASKER CERTIFIED SOLUTION
Avatar of SidFishes
SidFishes
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
With insert/update query you can add result attribute to check number of rescords being updated.
To avoid duplicates, you may check the existence of record matching the pk or fk.

If record exists, may be you want to run update query.

for example

<cfquery datasource="#request.dsn#" name="saveChanges" result="updateResult">
UPDATE table_name
SET
column1 = '#value1#',
column2 = '#value2#'
WHERE column3 = 1
</cfquery>

<cfset recordsChanged = updateResult.recordCount>