Let me explain a little.
Image you have the flowing MySQL table:
CREATE TABLE test (
value DATETIME
);
Currently I am doing something like this:
command.CommandText = "UPDATE test SET value = ?value";
command.Parameters.AddWithValue("?value", DateTime.Now);
But the clients date/time settings are unreliable so I would like the time to be determined at the server. Something like:
command.CommandText = "UPDATE test SET value = NOW()";
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.
For simplicity lets go back to the previous example.
As far as I can find I have two choices.
bool switch;
....
command.CommandText = "UPDATE test SET value = " + switch ? "NOW()" : "?value";
command.Parameters.AddWithValue("?value", value);
OR
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);
I don't like neater of them. Wouldn't it be neat if I could开发者_JAVA百科 do something similar to:
command.CommandText = "UPDATE test SET value = ?value";
if (switch) {
command.Parameters.AddWithValue("?value", "NOW()");
} else {
command.Parameters.AddWithValue("?value", value);
}
That way I would still execute the same one query.
Waiting for your opinions on this. I will be very grateful for any help you can provide.
You could use a stored procedure with an optional parameter to achieve this. If the parameter is NULL, you use NOW() instead. Although I'm not a big fan of stored procs (they are evil ! :-).
You could also use IFNULL(). Here is how it is done in T-SQL (function name is ISNULL) :
UPDATE test SET value = ISNULL(@value, GetDate() )
精彩评论