Soujanya
Soujanya

Reputation: 287

How to insert data, If that data does not exist in database using coldfuison?

I am working with Coldfusion. I am new to the language.

My requirement is to Insert data into database, only if a record not present. If it does exist in database, I want to throw error message.

Please help me how to do this .

Upvotes: 0

Views: 259

Answers (1)

Rino Raj
Rino Raj

Reputation: 6264

<cfquery name="qGetRecord" datasource="yourSorce"> 
    <!--- Your SELECT Query for finding the data--->
</cfquery> 

<cfif qGetRecord.recordCount EQ 0>
    <!--- Your INSERT Query --->
<cfelse>
    <!--- Show eroor message --->
</cfif>

The logic is that , first we will try to fetch the required data. Recordcount function is used to find if there is any matching records.
If matching record is not there then we can insert else show error message.

Updated answer with cftransaction as per the suggestion.

<cftransaction>
    <cftry>
        <cfquery name="qGetRecord" datasource="yourSorce"> 
            <!--- Your SELECT Query for finding the data--->
        </cfquery> 

        <cfif qGetRecord.recordCount EQ 0>
            <!--- Your INSERT Query --->
        <cfelse>
            <!--- Show eroor message --->
        </cfif>
        <cfcatch>
            <cftransaction action="rollback" />
        </cfcatch>
    </cftry>
</cftransaction> 

Upvotes: 1

Related Questions