I am trying to view the entries into my sql database that were entered within the last 24 hours. My database has a Date and Time field that are set when the record is entered. I am currently using the following code but it is not working. The is code executed correctly so I suspect that my SQL query is incorrect.
DateTime Time = DateTime.Now;
Time = Time.Subtract(new TimeSpan(24, 0, 0)); //Get DateTime of 24 Hours Ago
SqlDataSource1.SelectCommand = "SELECT * FROM DataTable WHERE Date>'" + Time.ToShortDateString() + "' AND Time>'" + Time.ToShortTimeString() + "'";
My Table name is correct and the field names are correct.
Thanks
You need to delimit your field names since they are reserved keywords:
SqlDataSource1.SelectCommand =
"SELECT * FROM DataTable WHERE [Date]>'" + Time.ToShortDateString() + "' AND [Time]>'" + Time.ToShortTimeString() + "'"
This is a very good reason to choose field names that are not reserved words in SQL.
If these are both one field, then you can just do a single evaluation of Date and Time:
WHERE <datetime field name> > GetDate() - 1
SELECT * FROM DataTable WHERE [DATE] > getdate() - 1
Related
This is in Microsoft SQL Server Management Studio; I have a column Order_Date in my table, and the data type is datetime.
In my ASP.NET web application, I am inserting the date using this query:
"INSERT INTO Order (ORDER_DATE) VALUES ('" + System.DateTime.Now + "')";
I've done the same thing before in another project but didn't get error there. Here I'm getting error when try to insert data. How can I solve this error?
System.DateTime.Now will automatically be converted to a string by C# when it is appended to your INSERT string. However the string it produces will be dependent on the regional/culture settings on the box on which it is executing. It is exceptionally unlikely to produce a datetime string format that SQL understands. So you need to ensure that the correct format is used by explicitly setting it when the string is generated:
"INSERT INTO Order (ORDER_DATE) Values ('" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')";
You could just make it a SqlType like:
"INSERT INTO Order (ORDER_DATE) Values ('" + new System.Data.SqlTypes.SqlDateTime(DateTime.Now).ToString() + "');"
Check out:
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqltypes.sqldatetime
I have 2 controls taking input of the date and time separately. Namely txtDateOutGv for the date and txtNewActionTimeOutGv for the time in hh:mm tt format from a time picker control.
I have tried many ways to insert into my SQL Server 2012 database and have never been able to successfully save the time. The saved time is always 2014-10-04 00:00:00
What is the approach for this? I have tried using stored procedures and it didn't work either.
Dim strActionTimeOut As String = DirectCast(gvActions.FooterRow.FindControl("txtDateOutGv"), TextBox).Text + " " + Convert.ToDateTime(Request.Form(DirectCast(gvActions.FooterRow.FindControl("txtNewActionTimeOutGv"), TextBox).UniqueID)).ToString("HH:mm:ss")
Dim actionTimeOut As DateTime
actionTimeOut = DateTime.ParseExact(strActionTimeOut, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)
actionTimeOut = Format(Convert.ToDateTime(strActionTimeOut), "yyyy-MM-dd HH:mm:ss")
insertAction As String = "INSERT INTO Actions([TimeOut]) VALUES ("+ CONVERT(date, CONVERT(DATETIME, '" + actionTimeOut + "', 0), 120)" + ")"
The time format should be as converted in the SQL Server too.. Not sure if that is the issue.
Yes, your code does exactly that:
CONVERT(date, CONVERT(DATETIME, '" + actionTimeOut
You convert the input value to a datetime (unnecessary) and then to a date. The last convert will loose all time info, as expected.
Use a datetime parameter:
SqlCommand cmd = new SqlCommand("INSERT INTO Actions([TimeOut]) VALUES (#actionTimeOut);");
cmd.Parameters.AddWithValue("#actionTimeOut", actionTimeOut);
cmd.Execute(...);
Seconds will always 00 when using SmallDateTime; seconds supplied will be rounded.
Also, don't use 'HH' for the 'hour' time format, use 'hh'. This will be the same regardless of whether you're using stored procs, direct SQL or a data layer.
Can you try this as a test. Sorry I wrote it in C# but you get the idea; it's just a test to insert a single hard-coded value using the format as shown below. This works for me here - if it doesn't work for you, it's almost certainly the format of your date. Again, note I am not supplying seconds as a parameter because SmallDateTime does not store it: -
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Actions([TimeOut]) VALUES ('2014-01-01 17:30')", conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
I have a problem. I need insert DateTime into SQL from ASP.NET. I have a calendar for inserting date and two DropDownlist. One for hours and other for minutes. I don't know how insert date from calendar and time (hours and minutes) all at once. This code insert only date. For example 28.3.2013 0:00:00.
cmd.CommandText = "insert into Milniky ( datetime ) values ('" + CalendarDz.SelectedDate + DropDownListHz + DropDownListMz +"')";
You should consider creating a DateTime object and parameters while inserting to prevent bad data.
int hour = int.Parse(DropDownListHz.SelectedValue);
int minute = int.Parse(DropDownListMz.SelectedValue);
DateTime dt = CalendarDz.SelectedDate;
dt.AddHours(hour);
dt.AddMinutes(minutes);
cmd.CommandText = "insert into Milniky ( datetime ) values (#dt)";
cmd.Parameters.Add(new SqlParameter("#dt", dt.ToString("yyyy-MM-dd HH:mm:ss")));
You may also want to use DateTime.TryParse(s) to give a better user experience
However in your specific command, I suspect you need to add a space and a colon to the statement to concatenate a date.
Currently your command looks like it's creating something like 2013-3-28130 and what you want is something like 2013-3-28 1:30.
cmd.CommandText = "insert into Milniky ( datetime ) values ('" + CalendarDz.SelectedDate.ToString("MM/dd/yyyy") + " " + DropDownListHz + ":" + DropDownListMz +"')";
I am using multiview index to insert the news details. In the first view the user can enter details of news which is then inserted into db on clicking the next button
the second view gives a user to add images of that news (only 3 images allowed) ,
what I am having problem is that the first view inserts data into the table dbo.newsdetail with a primary key
newsID , while the second view should add the respected images using that newsId of the news just added into newsimages table. I just dont know how to get the newsID of the details
which is added in the first view as news Id is working as a foreign key for the both the table. Any help or suggestions will be highly appreciated .
static public void insertNews(string newsDescription, string newsImage, string newsTitle)
{
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlCommand insertNews = new SqlCommand("Insert INTO caravanNews(newsDescription, newsImage, newsTitle) VALUES ('" + newsDescription + "', '" + newsImage + "' , '" + newsTitle + "')",conn);
insertNews.ExecuteNonQuery();
conn.Close();
}
A separate SQL statement
SELECT SCOPE_IDENTITY()
Or the OUTPUT clause
INSERT MyTable (...=
OUTPUT INSERTED.KeyCol
VALUES (...) --Or SELECT ... FROM Another table)
Edit:
change your insert statement to match mine
change .ExecuteNonQuery() to blah = xxx.ExecuteScalar()
As part of your INSERT statement (into the first News table), after it runs, execute
SELECT SCOPE_IDENTITY()
and return NewsId value to caller.
Ref.
I'm setting a Session of MM_CustomerID in my code and then further down the page I need to insert the value of that session into a table. But each time I try to do this it comes up with an Invalid column name 'varCustomerID'.
At the top of the page I have this code;
<%
set rscustomerid = Server.CreateObject("ADODB.Recordset")
rscustomerid.ActiveConnection = CmdAddCustomer.ActiveConnection
rscustomerid.Source = "SELECT ##IDENTITY as MaxCustomersID FROM Customers"
rscustomerid.CursorLocation = 2
rscustomerid.LockType = 3
rscustomerid.Open()
Session("MM_CustomerID")=rscustomerid("MaxCustomersID")
Session("MM_UserAuthorization") = "5"
%>
Then further down, i'm trying to set a variable of varCustomerID to be equal to the MM_CustomerID session;
<%
varCustomerID = Session("MM_CustomerID")
%>
And then try inserting the value of that variable varCustomerID into the Orders table as follows;
<%
'Insert record into Orders recordset when form is submitted
'and store the unique OrderID
'Version Date: 09 August 2009
set CmdAddOrder = Server.CreateObject("ADODB.Command")
CmdAddOrder.ActiveConnection = MM_dbconn_STRING
CmdAddOrder.CommandText = "INSERT INTO Orders (OrderCustomer,OrderGrandTotal,OrderStatus) VALUES (varCustomerID,0.00,3)"
CmdAddOrder.CommandType = 1
CmdAddOrder.CommandTimeout = 0
CmdAddOrder.Prepared = true
CmdAddOrder.Execute()
%>
I wondered if anyone might be able to help? Perhaps there's an easier way of just inserting the session value into the table, instead of creating a variable for it?
Thanks.
You need to change the sql command text to:
"INSERT INTO Orders (OrderCustomer,OrderGrandTotal,OrderStatus) VALUES (" + varCustomerID + ",0.00,3)"
However you could be vulnerable to SQL injection... really you should parametrise this query:
http://aspnet101.com/aspnet101/tutorials.aspx?id=1
You need to cast varCustomerID to a string for the query. Slight change to Paul's answer should get you working but like he says you need to be careful of injection attacks.
"INSERT INTO Orders (OrderCustomer,OrderGrandTotal,OrderStatus) VALUES (" & varCustomerID & ",0.00,3)"