Search code examples
mysqlcoldfusioninsert-intocfquery

Insert query error: Column count doesn't match value count at row 1


I have a cfquery that I'm looping over the values to insert multiple rows into the database. I have to do it this way, instead of generating multiple INSERT queries within a loop, because I need a list of the generatedKeys after the INSERT. However my query is now throwing the error below. I know what the error means, but it doesn't make sense based off my query.

Query:

<cfquery datasource="#OLMSdatasourceWrite#" result="myResult">
    INSERT INTO OLMS_Data_RatioScenarios
    (
        OLMS_Account_ID,
        OLMS_RatioScenario_Name
    )
    VALUES
    (
    <cfset numItems = ListLen(AccountListWithSettings)>
    <cfset i = 1>

    <cfloop list="#AccountListWithSettings#" index="CurrentAccount">
        (<cfqueryparam cfsqltype="cf_sql_numeric" value="#CurrentAccount#" maxlength="255">
        , <cfqueryparam cfsqltype="cf_sql_clob" value="#requestBody.value#" maxlength="255">
        )
        <cfif i lt numItems>
            ,
        </cfif>

        <cfset i++>
    </cfloop>
    )
</cfquery>

<cfoutput>Inserted ID is: #myResult.generatedkey#</cfoutput>

Error:

Root Cause:java.sql.SQLException: Column count doesn't match value count at row 1
SQL: INSERT INTO OLMS_Data_RatioScenarios ( OLMS_Account_ID, OLMS_RatioScenario_Name ) 
VALUES ( ( (param 1) , (param 2) ) , ( (param 3) , (param 4) ) , ( (param 5) , (param 6) ) ) 

Solution

  • Corrected Code:

    <cfquery datasource="#OLMSdatasourceWrite#" result="myResult">
        INSERT INTO OLMS_Data_RatioScenarios
        (
            OLMS_Account_ID,
            OLMS_RatioScenario_Name
        )
        VALUES
        <cfset numItems = ListLen(AccountListWithSettings)>
        <cfset i = 1>
        <cfloop list="#AccountListWithSettings#" index="CurrentAccount">
            (
              <cfqueryparam cfsqltype="cf_sql_numeric" value="#CurrentAccount#" maxlength="255">
             , <cfqueryparam cfsqltype="cf_sql_clob" value="#requestBody.value#" maxlength="255">
            )
            <cfif i lt numItems>
                ,
            </cfif>
    
            <cfset i++>
        </cfloop>
    </cfquery>