Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pass a MySQL database function as a query parameter from c#
    primarykey
    data
    text
    <p>Let me explain a little.</p> <p>Image you have the flowing MySQL table:</p> <pre><code>CREATE TABLE test ( value DATETIME ); </code></pre> <p>Currently I am doing something like this:</p> <pre><code>command.CommandText = "UPDATE test SET value = ?value"; command.Parameters.AddWithValue("?value", DateTime.Now); </code></pre> <p>But the clients date/time settings are unreliable so I would like the time to be determined at the server. Something like:</p> <pre><code>command.CommandText = "UPDATE test SET value = NOW()"; </code></pre> <p>The trick is that I want to pass the "NOW()" function as a parameter to the original query. Please understand that this small example is OVERLY simplified. In reality the table has 48 columns, 7 of which are datetime, marking the date and/or time the user made a particular operation to the object the database row denotes. When the user performs a new operation to the object I read the entire row and insert it again, with a different ID of course, (Something like a poor man's revision history) so I like to keep the date/time of the old operation and insert it in the new row, but at the same time set the current date/time (as seen by the database) for the new operation.</p> <p>For simplicity lets go back to the previous example.</p> <p>As far as I can find I have two choices.</p> <pre><code>bool switch; .... command.CommandText = "UPDATE test SET value = " + switch ? "NOW()" : "?value"; command.Parameters.AddWithValue("?value", value); </code></pre> <p>OR</p> <pre><code>bool switch; .... if (switch) { command.CommandText = "SELECT NOW()"; value = Convert.ToDateTime(command.ExecuteScalar()); } command.CommandText = "UPDATE test SET value = ?value"; command.Parameters.AddWithValue("?value", value); </code></pre> <p>I don't like neater of them. Wouldn't it be neat if I could do something similar to:</p> <pre><code>command.CommandText = "UPDATE test SET value = ?value"; if (switch) { command.Parameters.AddWithValue("?value", "NOW()"); } else { command.Parameters.AddWithValue("?value", value); } </code></pre> <p>That way I would still execute the same one query.</p> <p>Waiting for your opinions on this. I will be very grateful for any help you can provide.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload