Trying to set a datetime field in a SQL table to NULL if the textbox is empty, I can't seem to get this to work.
string EndDate = "";
if (String.IsNullOrEmpty(EndDateTxtBox.Text.Trim()))
{
EndDate = null;
}
else
{
EndDate = EndDateTxtBox.Text;
}
var sql = String.Format(#"UPDATE Test SET StartDate='{0}',
EndDate='{1}' WHERE ID = '{2}'",
StartDateTxtBox.Text, EndDate, id);
When I do this and put in a break point I get this for "var sql':
"UPDATE Test SET StartDate='5/23/2013', EndDate=" WHERE ID = '19'"
I tried removing the ' from the sql string but that didn't work either. Any suggestions?
Edit: I understand the importance of preventing against SQL injection but this a page on my internal web server for my use only and not projected to the public. It's to help me keep track of personal things.
Parameterize.
First, you should move the UI code away from the database code, so that by the time it gets anywhere near the DB we have correctly typed data. For example:
void UpdateDates(int id, DateTime startDate, DateTime? endDate) {...}
and put whatever Parse etc code you want at the caller - not near the db. Now we need to implement that:
void UpdateDates(int id, DateTime startDate, DateTime? endDate) {
//... where-ever cmd comes from, etc
cmd.CommandText =
"update Test set StartDate=#start, EndDate=#end where ID = #id";
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters.AddWithValue("start", startDate);
cmd.Parameters.AddWithValue("end", (object)endDate ?? DBNull.Value);
cmd.ExecuteNonQuery();
// ... cleanup etc
}
Or with a tool like "dapper":
void UpdateDates(int id, DateTime startDate, EndDate? endDate) {
//... where-ever connection comes from, etc
connection.Execute(
"update Test set StartDate=#start, EndDate=#end where ID = #id",
new { id, start = startDate, end = endDate}); // painfully easy
// ... cleanup etc
}
It sounds like the problem is the single quotes. If it is NULL then you shouldn't have them.
Also, you probably want to be using a parameterized query (for safety reasons and pass in the values). In that case the quotes shouldn't be necessary either.
Notwithstanding the issues in your code that are not regarded as SQL best practices within C# code, you have several issues:
You're setting EndDate to a C# null. That is not the same as an SQL NULL, which is denoted as DBNull.Value
You have no regard for the fact that NULL doesn't need quotes in SQL, so your SQL would need to be different anyway in order to work even if you fix #1.
I suggest to write a Stored Procedure; if the end date textbox is null, just don't pass that parameter, and make it have a default value of NULL in the stored proc.
Create Procedure usp_TestDateRange_Update
( #ID int -- or whatever type your ID is
#StartDate DateTime,
#EndDate DateTime = NULL)
As
Update Test
Set StartDate = #StartDate,
EndDate = #EndDate
Where ID = #ID
Something like that. Now what you need to do is make your C# code call the stored procedure and add the parameters to the call from your textboxes.
I think the error is in the string.format line. you cannot include a line break in the string portion. Try one of the following.
var sql = String.Format(
#"UPDATE Test SET StartDate='{0}', EndDate='{1}' WHERE ID = '{2}'",
StartDateTxtBox.Text, EndDate, id);
or,
var sql = String.Format(#"UPDATE Test SET StartDate='{0}', " +
"EndDate='{1}' WHERE ID = '{2}'",
StartDateTxtBox.Text, EndDate, id);
but, as other answers here mention, you should learn about SQL injection and consider another approach.
You can try this way:
string sql = String.Format(#"UPDATE Test SET StartDate={0},
EndDate={1} WHERE ID = {2}",
(StartDateTxtBox.Text.Trim().Equals(string.Empty) ? StartDateTxtBox.Text:"NULL"), EndDate, id);
Related
How to add parameters in a SQL select query?
string time = 2013-09-25 00:00:00;
I wish to use the time variable in the below mentioned SQL query
Select LastUpdated from Employee where LastUpdated > time;
Try this:
string sqlDate = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
It appears what the OP is asking is how to convert a VARCHAR to a DATETIME in SQL Server not actually a String to DateTime in C#.
You will need to use the following to convert to a DATETIME:
SELECT LastUpdated
FROM Employee
WHERE LastUpdated > CONVERT(datetime, varTime, 121);
See the following MS Reference for more information.
To echo others though, you should just pass the parameter in as a datetime and let the database provider factory handle the conversion of appropriate types, or add a new method that actually returns a DateTime. In the future, I wouldn't name a method GetUpdateTime unless it actually returns a type of Time.
You can convert your string in C# code to DateTime using
DateTime.TryParse() or Convert.ToDateTime()
OR
Convert VARCHAR to DATETIME in SQL using
Convert(datetime, time)
I just framed my question in a wrong, the query remains the same though. I just wanted time to be added as a paramter in my SQL-query. The code for the same looks like
String commandText = "Select LastUpdated from Employee where LastUpdated > :time;";
OracleConnection connection = new OracleConnection(connectionString);
OracleCommand command = new OracleCommand(commandText, connection);
command.Parameters.Add("time", time);
Thanks a lot for your help!
My bad that I couldn't frame the question properly.
I have a SQL query that I am passing a C# variable into my Oracle DB.
I am having trouble passing a C# datetime variable, "PROCESS_DATE", into my query in my application. I do not get any records back. If I copy the query into my oracle developer tool, TOAD, it works fine and I get multiple records.
Here is the query I am using in my application:
String SelectAllSQL = "SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = :pPROCESS_DATE";
I also tried converting the datetime variable into a shortDateString() so it matches the database exactly I then used the TO_DATE function, which I have to use if I query dates directly in TOAD, without any luck. The shortDateString() changes my date into: 1/16/2016, which is what I need, but the OracleDataReader does not like it. Here it the query with the TO_DATE function:
String SelectAllSQL = "SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = TO_DATE(:pPROCESS_DATE, 'MM-DD-YYYY'";
:pROCESS_DATE is a datetime variable that is passed in.
There must be a breakdown between C# and Oracle in relation to handling a datetime variable. I am using Oracle DataReader to handle the processing of the query.
OracleDataReader dataReader = mDataAccess.SelectSqlRows ( oracleConnection, oracleCommand, sqlCommand, parameters );
while ( dataReader.Read ( ) )
{
groupEntityFacilityRptList.Add ( ReadRecord ( dataReader ) );
}
If I use the TO_DATE function, the application will not step into the while loop. If I use the original query, it does but returns no data.
The datetime variable PROCESSDATE looks like this:
1/16/2016 12:00:00 AM
I notice it has a timestamp on it, so I'm not sure if that is the problem or not.
The data in Oracle is like this:
1/16/2016
Unless I've totally misunderstood your issue, I think you might be making this harder than it needs to be. ODP.net handles all of that dirty work for you. If PROCESS_DATE is an actual DATE datatype in Oracle, then you just need to pass an actual C# DateTime variable to it and let ODP.net do the heavy lifting. There is no need to do conversion of any type, provided you are passing an actual date:
DateTime testDate = new DateTime(2015, 7, 16);
OracleCommand cmd = new OracleCommand(
"SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = :pPROCESS_DATE",
conn);
cmd.Parameters.Add(new OracleParameter("pPROCESS_DATE", OracleDbType.Date));
cmd.Parameters[0].Value = testDate;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
object o = reader.IsDBNull(0) ? null : reader.GetValue(0);
}
reader.Close();
If your data in C# is not a date, I'd recommend making it one before even trying:
DateTime testDate;
if (DateTime.TryParse(testDateString, out testDate))
{
// run your query
}
As per my comment, please try below and see this resolves.
TRUNC(TO_DATE(:pPROCESS_DATE,'MM-DD-YYYY HH:MI:SS AM')) if pROCESS_DATE format is 1/16/2016 12:00:00 AM.
TRUNC(TO_DATE(:pPROCESS_DATE,'DD-MM-YYYY HH:MI:SS AM')) if pROCESS_DATE format is 16/1/2016 12:00:00 AM.
First, I learned that my code will not go into the code below unless I actually have records returned to me.
OracleDataReader dataReader = mDataAccess.SelectSqlRows ( oracleConnection, oracleCommand, sqlCommand, parameters );
while ( dataReader.Read ( ) )
{
groupEntityFacilityRptList.Add ( ReadRecord ( dataReader ) );
}
Second, to get ProcessDate to work, I needed to take the string that was coming from my View, convert it to a datetime, and then I formatted it back as a string. It may not be best practices but it worked.
public JsonResult GetGroupReportData ( String reportDate )
{
DateTime processDate = DateTime.Parse ( reportDate );
var monthlyReport = SelectAllGroupRprt (processDate.ToString("MM/dd/yyyy");
return new JsonResult ( )
{
Data = monthly,
MaxJsonLength = Int32.MaxValue
};
}
After i create an insert statement i want to know two values, the last inserted id and the date.
This is my insert statement
cmd.CommandText = "INSERT INTO message (user_id, category_id, media) " +
"VALUES (:user_id, :category_id, :media)" +
"RETURNING id, TO_DATE(TO_CHAR(creation_date, 'YYYY-MM-DD HH24:MI:SS'), 'YYYY-MM-DD HH24:MI:SS') INTO :last_insert_id, :last_creation_date";
The parameter
cmd.Parameters.Add(new OracleParameter()
{
ParameterName = ":last_creation_date",
OracleDbType = OracleDbType.Date,
Direction = ParameterDirection.Output
});
When i try to get the date, only the year, month and day returns with 00:00:00...
DateTime.Parse(cmd.Parameters[":last_creation_date"].Value.ToString())
How can i receive the full datetime from the value?
A couple of things:
Take a look at the docs for OracleDbType. You are using OracleDbType.Date, which maps to an Oracle DATE type - which is just a date. You should probably use OracleDbType.TimeStamp, or whatever type matches the column you're working with.
Mitch is correct in the question comments. You have entirely too much conversion to and from strings. In the vast majority of cases, you should not use a string to represent a date or time in a database, or in the client code that communicates with a database. Your SQL should change simply to:
RETURNING id, creation_date INTO :last_insert_id, :last_creation_date
Likewise, your .NET code should be similar to:
DateTime dt = (DateTime) cmd.Parameters[":last_creation_date"].Value;
I have to following parameters that are necessary to execute a stored procedure in sql server 2008 r2
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate.ToString());
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate.ToString());
da.SelectCommand.Parameters.AddWithValue("#PaymentType", payment.ToString());
These are necessary to execute a stored procedure. All of the session variables are passed correctly. However when the gridview renders it shows no data. I know there is data because I can run the stored procedure on SSMS and it runs perfectly with the parameters that are passing to the proc (when I input them).
I am pretty confused at this point so any help would be helpful.
grdDenialDetail.DataSource = ds.Tables["DetailDenial"].DefaultView;
grdDenialDetail.DataBind();
ENTIRE ROUTINE: (maybe this will help)
public void ExecuteDetailReport()
{
string sessionConnection = Session["Company"].ToString();
string sessionStartDate = Session["StartDate"].ToString();
string sessionEndDate = Session["EndDate"].ToString();
string payment = Session["payment"].ToString();
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings[sessionConnection].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("dbo.cusGenDenialReportPivotStylePType", conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
/*da.SelectCommand.Parameters.Add(new SqlParameter("#StartDate", SqlDbType.VarChar, 11)).Value = sessionStartDate.ToString();
da.SelectCommand.Parameters.Add(new SqlParameter("#EndDate", SqlDbType.VarChar, 11)).Value = sessionEndDate.ToString();
da.SelectCommand.Parameters.Add(new SqlParameter("#PaymentType", SqlDbType.VarChar, 100)).Value = payment.ToString();*/
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate);
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate);
da.SelectCommand.Parameters.AddWithValue("#PaymentType", payment);
lblTest.Visible = true;
lblTest.Text = "You selected " + payment + ".";
DataSet ds = new DataSet();
da.Fill(ds, "DetailDenial");
grdDenialDetail.DataSource = ds.Tables["DetailDenial"].DefaultView;
grdDenialDetail.DataBind();
da.Dispose();
conn.Close();
}
I think your issue is related to the fact that you are using and comparing dates as strings and not dates. Your result set is empty because your query is trying to compare date strings alphabetically instead of chronologically. To refactor your code, I would make sure that you address the following areas:
Setting the session variables
Carefully parse the dates out of your text fields.
DateTime startDate;
if (DateTime.TryParseExact(txtStartDate.Text, "MM/dd/yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out startDate))
{
Session["StartDate"] = startDate;
}
DateTime endDate;
if (DateTime.TryParseExact(txtEndDate.Text, "MM/dd/yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out endDate))
{
Session["EndDate"] = endDate;
}
You may want to handle the case when the TryParseExact methods return false (parse failure).
Retrieving session variables
We set the session variables as DateTime objects, so cast them back upon retrieval:
var sessionStartDate = (DateTime)Session["StartDate"];
var sessionEndDate = (DateTime)Session["EndDate"];
Notice we're still using native .NET types here.
Setting up your query parameters
Use the .Date property of the DateTime struct to drop the time component:
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate.Date);
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate.Date);
...
And lastly, update your stored procedure so that its parameters are of type date:
CREATE PROCEDURE dbo.cusGenDenialReportPivotStylePType
(
#StartDate date = null,
#EndDate date = null,
...
)
AS
...
SELECT
*
FROM
Somewhere
WHERE
TheDate BETWEEN #StartDate AND #EndDate
Keeping everything in its native data format will make your life a lot easier.
Remove .ToString() calls from your code.
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 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() )