Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i reuse bind variable in an 'insert ... on duplicate update ...' statement?

Tags:

sql

mysql

I am attempting to run a query that uses bind variables against a mysql database engine. I am wondering how I can tell the engine to "reset" the bind variable assignments. I'm sure an example will explain much better than my poor brain.

Here is the query:

INSERT INTO site_support_docs
      (
          ASSET_ID,
          TIME_STAMP,
          SITE_NAME,
          DOCUMENT_NAME,
          DOCUMENT_LOCATION,
          DOCUMENT_CONTENT,
          DOCUMENT_LAST_MODIFIED
      )
VALUES (?, ?, ?, ?, ?, ?, STR_TO_DATE(?, '%M %e, %Y %r'))
ON DUPLICATE KEY UPDATE asset_id   = ?,
                        time_stamp   = ?,
                        site_name   = ?,
                        document_name   = ?,
                        document_location   = ?,
                        document_content   = ?,
                        document_last_modified   =
                           STR_TO_DATE(?, '%M %e, %Y %r')

My problem is that the eighth "?" is interpreted as a new bind variable when there are only seven. Anyway, I guess I can revert to using the actual values... but, I'm sure there is a better way. Matt

like image 655
Matt Cummings Avatar asked Mar 01 '23 19:03

Matt Cummings


1 Answers

MySQL offers a "VALUES()" function that provides the value which would have been inserted had the duplicate key conflict not existed. You don't need to repeat the placeholder then.

INSERT INTO t VALUES (?) ON DUPLICATE KEY UPDATE x = VALUES(x);

http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_values

like image 85
Scott Noyes Avatar answered Mar 03 '23 16:03

Scott Noyes