代码之家  ›  专栏  ›  技术社区  ›  CFML_Developer

如何知道upsert查询中运行的内容

  •  0
  • CFML_Developer  · 技术社区  · 6 年前

    我有个问题

    <cfquery name="qryTemp" datasource="someDSN">
    if not exists (select someID from tempTable where someID = 20)
    insert into tempTable (someID, colA, colB) values (1,2,3)
    else
    update tempTable set
    colA = 2, colB =3
    where someID = 1
    </query> 
    

    是否有任何标识符可以指出它是插入还是更新?如果有帮助的话,我可以将result属性添加到查询中。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Matthew Moore    6 年前

    我会尝试给 cfquery 标记结果参数,并检查该结果是否具有插入ID:

    编辑:使用的函数不会使 <cfif> .

    <cfquery name="qryTemp" datasource="someDSN" result="local.results">
    if not exists (select someID from tempTable where someID = 20)
    insert into tempTable (someID, colA, colB) values (1,2,3)
    else
    update tempTable set
    colA = 2, colB =3
    where someID = 1
    </query>
    
    <cfif structKeyExists(local.results, 'GENERATEDKEY')>
    Do your stuff here...
    </cfif>
    

    (检查 Documentation 看哪一个 GENERATEDKEY 最适合你的目的)

        2
  •  1
  •   SOS    6 年前

    为了提供另一个选项,sql 2008+还支持 MERGE 对于“upserts”。添加output子句将提供对 $action 变量。顾名思义,它将指示实际执行的操作(“插入”或“更新”)。

    <cfquery name="qryTemp" datasource="#someDSN#">
        MERGE INTO tempTable tmp
        USING ( VALUES ( 1, 2, 3 )) 
            AS data (someID, colA, colB) 
            ON data.someID = tmp.someID
        WHEN MATCHED THEN
            UPDATE SET tmp.ColA = data.ColA
                , tmp.ColB = data.ColB
        WHEN NOT MATCHED THEN
            INSERT (someID, colA, colB)
            VALUES (data.someID, data.colA, data.colB)
        OUTPUT inserted.someID AS ModifiedID
                , $action AS Action;
    </cfquery>
    
    <!--- Demo: Was an insert or update peformed? --->
    <cfif qryTemp.Action eq "INSERT">
        ID inserted = <cfoutput>#qryTemp.ModifiedID#</cfoutput>
    <cfelse>
        ID updated = <cfoutput>#qryTemp.ModifiedID#</cfoutput>
    </cfif>
    

    NB:尽管是开箱即用, concurrency is still an issue 无论哪种方法。