views:

183

answers:

3

Hello,

I am trying to fire Update Query using cfquery like below

   <cfquery name = "UpdateRecord"   
            dataSource = #DATASOURCE#   
            username = #DBUSER#   
            password = #DBPASSWORD# 
            result="updateResult" >  
        update table1 
set field1=( select field1 from table2 where field3='Some Value')
 where field4='someothervalue'
     </cfquery> 
    <cfdump var="#UpdateResult#">

But, when I execute this page, the page is not loading, in status bar I can see its loading for long time.

But If I use any simple Update Query like

update table1 set field1='abc' where field4='someothervalue'

then it is working fine

Can any one has idea how can I execute the queries like above using cfquery?

Thanks

A: 

Are you sure your subselect statement is returning 1 row. It depends on what RDMS you are running, but I'm pretty sure not all databases support this feature. I'd try running the query directly on your database first to see if it runs correctly.

You might be able to force sql to return only 1 row by putting a limit 1 on the end of your query, or if your database doesn't support it wrapping field1 in an aggregate.

SELECT MAX(field1) FROM table2 WHERE field3 = 'Some Value'

Note: If your String values are parameters from the user, you should make sure to use cfqueryparam to protect against SQL injection.

mountainswhim
Yes, I tried teh same stament on Directly DB, it worked fine there, but its not working if i use cfquery. and my select statement gives only one output. Can we use paranthesis '(',')' in cfquery?
CFUser
Where are you using '(',')' in the query you posted? There is nothing wrong with using parenthesis. It is likely an issue with your single quotes. When you do not use cfqueryparam CF takes a few steps to help protect you from yourself ;) See my reply to @jarofclay.
Leigh
+1  A: 

Did you try wrapping your update within PreserveSingleQuotes?

 <cfquery name = "UpdateRecord"   
        dataSource = #DATASOURCE#   
        username = #DBUSER#   
        password = #DBPASSWORD# 
        result="updateResult" >  
   #PreserveSingleQuotes(update table1 set field1=( select field1 from
   table2 where Field3='Some Value') where field4='someothervalue')#
 </cfquery>
kevink
Yes.. It worked with PreserveSingleQuotes, thanks
CFUser
I agree with jarofclay, now that it works the next step should be to convert it to use cfqueryparam
kevink
+2  A: 

If you can try using cfqueryparam for your values and you won't have to use PreserveSingleQuotes. It also protects against SQL injection.

jarofclay
+1 . CF automatically escapes quotes to mitigate sql injection risks. PreserveSingleQuotes() dismantles that protection and can expose databases to sql injection. Do not use PreserveSingleQuotes() unless it is really needed and you understand the risks. Plus, with cfqueryparam you get some performance benefits from bind variables.
Leigh