Sql query with the current date - c#

I've got a simple query where I want to put the current date
var query = #"
SELECT trainid, trainnum
FROM trains
WHERE CONVERT(varchar(10), trainstartdate, 104)=" +
" " +
// so that matches the '104' format
String.Format("{0:dd.MM.YYYY}", DateTime.Now) +
" " +
"ORDER BY trainnum";
But when running I get the error message:
Cannot call methods on numeric. .Net SqlClient Data Provider
How do I specify current date the right way?
Thanks!
Using GETDATE()
Effect:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
Using {0:dd.MM.yyyy}
Effect: none
Using CONVERT(varchar(20), GetDate(), 104)
Effect: that works!
Thanks!

Description
I would not convert to a varchar and doing string comparrisson. The performance is much better if you compare trainstartdate using the >= and <.
You can use the T-SQL getDate() method to get the current date.
getDate() returns the current datetime with the time. 2012-02-14 14:51:08.350
DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) return only the current date. `2012-02-14 00:00:00.000
DATEADD(dd, 1, DATEDIFF(dd, 0, GETDATE())) returns only the date of tomorow. 2012-02-15 00:00:00.000
Sample
var query = #"
SELECT trainid, trainnum
FROM trains
WHERE trainstartdate >=
-- today
DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
AND trainstartdate <
-- tommorow
DATEADD(dd, 1, DATEDIFF(dd, 0, GETDATE()))
ORDER BY trainnum"
Note:
If you want to be ANSI compliant, CURRENT_TIMESTAMP does the same.
More Information
MSDN - GETDATE (Transact-SQL)
MSDN - DATEDIFF (Transact-SQL)
MSDN - DATEADD (Transact-SQL)
Stackoverflow - CURRENT_TIMESTAMP vs GetDate()

var query = #"
SELECT trainid, trainnum
FROM trains
WHERE CONVERT(varchar(10), trainstartdate, 104)=
CONVERT(varchar(20), GetDate(), 104)
ORDER BY trainnum";

GETDATE() is all you need...

I think
String.Format("{0:dd.MM.YYYY}", DateTime.Now);
is returning the date with a dot, which makes SQL consider it as a number.
Try using
String.Format("{0:MM/dd/yyyy}", DateTime.Now);
with a / instead.

Change the format pattern of YYYY to small-case letters
{0:dd.MM.yyyy}

You need to be aware that GETDATE() returns the current date and time of day, not only today's date.
If you want to return rows matching today's date, you need to extract the date part. There are a number of ways to do this - e.g. with SQL Server 2008 you can use the DATE data type, but one general way that works with earlier versions of SQL Server is the following:
CONVERT(DATETIME, convert(VARCHAR(10),getdate(),101) )
You can then use the query:
SELECT trainid, trainnum
FROM trains
WHERE trainstartdate = CONVERT(DATETIME, convert(VARCHAR(10),getdate(),101) )
which will work provided you are sure that the date/time in the trains.trainstartdate column is a date only (time of day = 0).
If trainstartdate contains the start date/time, you can get all of today's trains as follows:
SELECT trainid, trainnum
FROM trains
WHERE trainstartdate >= CONVERT(DATETIME, convert(VARCHAR(10),getdate(),101) )
AND trainstartdate < DATEADD(dd,1, CONVERT(DATETIME, convert(VARCHAR(10),getdate(),101) ))
By doing it like this rather than converting to a string, you will take advantage of any index there may be on the trainstartdate column.

Try this .. YYYY should be small letter yyyy
String.Format("{0:dd.MM.yyyy}", DateTime.Now)

Related

T-SQL SQL Server: Compare todays with future date in IF condition

I need to compare todays date with a future date using IF conditional in T-SQL SQL Server. It is contained in a store procedure which is called from C#. Also I want to return no rows if current date is not less or equal than future date.
So I have done:
DECLARE #FutureDate VARCHAR = '2017-05-20 00:00:00'
IF CAST(GETDATE() AS DATE) <= CAST(#FutureDate AS DATE)
BEGIN
....
END
ELSE
BEGIN
SELECT TOP 0 NULL
END
I call this store procedure from C#, But it is generating an error saying cannot convert into datetime. Time is not important for me, only date is important.
UPDATE:
Doing this is working and no need to convert FutureDate as DATE.
DECLARE #FutureDate DATE = '2017-05-20'
IF CAST(GETDATE() AS DATE) <= #FutureDate
BEGIN
....
Doing this is working and no need to convert FutureDate as DATE.
DECLARE #FutureDate DATE = '2017-05-20'
IF CAST(GETDATE() AS DATE) <= #FutureDate
BEGIN
....
END
ELSE
....
END

How to find time differences between two time in c#

I have a form that gives me time_in and time_out hours of all staff members. Time_in and time_out also sql tables. Basically form returns the database table values. What I would like to do is to display the work hour of them. Work hour can be get the differences from time_out to time_in. I have two text boxes that display time in and Time_out. The third one should display work hour.
Here is what I have for time_out value for Wednesday:
//Selected TimeOutWednesday
SqlCommand TimeOutWednesdayMain = cs.CreateCommand();
TimeOutWednesdayMain.CommandText = "SELECT CONVERT(VARCHAR(8), time_out, 108) AS time_out FROM job_punch_card WHERE emp_key='" + listBoxNames.SelectedValue.ToString() + "'and punch_day= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 2)";
Object TimeOutWednesdayMainTemp = TimeOutWednesdayMain.ExecuteScalar();
txtTimeInWed.Text = TimeOutWednesdayMainTemp.ToString();
This code gives me time_out for wednesday for the selected user from my listbox. I have the same code for time_in as well. What I couldn't do is to figure out how find the work hour? How can I display their work hour in a label or text box like I have above?
The DateTime types in OS are simples Integer values, you should make a arithmetical operation and get the Hours or TotalHours:
Hours get the integer portion of difference (dont lose parse your textboxes):
DateTime time_in;
DateTime.TryParse(time_in_TextBox.Text, out time_in);
DateTime time_out;
DateTime.TryParse(time_out_TextBox.Text, out time_out);
int hours = (time_in - time_out).Hours;
TotalHours get a double value with the exact difference in DateTimes:
DateTime time_in;
DateTime.TryParse(time_in_TextBox.Text, out time_in);
DateTime time_out;
DateTime.TryParse(time_out_TextBox.Text, out time_out);
double totalHours = (time_in - time_out).TotalHours;
I don't know if you're set on doing the time difference in SQL, but here's how you can do it in C# - though you would need to convert to a datetime object, not just a time (at least in this example).
See https://dotnetfiddle.net/DSuHmH :
using System;
public class Program
{
public static void Main()
{
DateTime startTime = new DateTime(2014, 1, 1, 1, 5, 1);
DateTime endTime = new DateTime(2014, 1, 1, 5, 10, 55);
TimeSpan ts = endTime - startTime;
Console.WriteLine(ts); // returns "04:05:54"
}
}
to specifically get the hours use:
ts.Hours;
To accomplish in sql you can do something like the following - again you'll need to convert your time to a datetime and then you can utilize the datediff function.
See: http://sqlfiddle.com/#!6/b7a7c/7
select convert(datetime, '2014-01-01 ' + startTime, 101),
convert(datetime, '2014-01-01 ' + endTime, 101),
datediff(
hh,
convert(datetime, '2014-01-01 ' + startTime, 101),
convert(datetime, '2014-01-01 ' + endTime, 101)
)
from test
Note that in the examples above i'm using an arbitrary date to accomplish creating a valid datetime
You should be able to do this in one query. This also shows the best practices for dealing with ADO.Net including putting your sql objects in using statements and passing values into your query as a parameter. Additionally you'll have to use ExecuteReader to get more than one value back and you can add checking for retrieving more or less than 1 row.
using (var cs = new SqlConnection("your connection string"))
{
cs.Open();
using (var command = cs.CreateCommand())
{
command.CommandText =
#"SELECT
time_in,
time_out,
DATEDIFF(minute, time_in, time_out) As minutesWorked
FROM job_punch_card
WHERE emp_key=#EMPKEY
and punch_day= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 2)";
command.Parameters.AddWithValue(
"#EMPKEY",
listBoxNames.SelectedValue.ToString());
using (var reader = command.ExecuteReader())
{
if (!reader.HasRows)
{
// There was no match for your key
}
reader.Read();
DateTime timeIn = reader.GetDateTime(0);
DateTime timeOut = reader.GetDateTime(1);
int minutesWorked = reader.GetInt32(2);
if (reader.Read())
{
// There was more than one match on key
}
}
}
}
You can get the time difference, in minutes, using this:
DATEDIFF(MINUTE, #punch_day, #time_out)
This will return the total minutes between the two dates. If you need hours, divide it by 60. If you need days, then divide it by (60*24). Should you need weeks, divide it by (60*24*7). If you need years, divide it by (60*24*365). You get the idea, I hope!
Check out this example:
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
SELECT #StartDate = '12/9/2014 11:04am'
SELECT #EndDate = '12/10/2014 1:38pm'
SELECT DATEDIFF(MINUTE, #StartDate, #EndDate) AS TotalMinutes,
DATEDIFF(MINUTE, #StartDate, #EndDate) / 60 AS TotalHours,
DATEDIFF(MINUTE, #StartDate, #EndDate) / (60*24) AS TotalDays

Month/Year SQL to correct format

I have a textfield that users input the date using a modified jquery datepicker. The textfield has the Month and Year such as 'July 2011'
I need to run a query to search for results between July 1, 2011 and July 31, 2011. My date in the database is a smalldatetime, so I need my query to look like this:
select * from members where signupdate between 'july 1 2011' and 'july 31 2011'
How can I get the user inputted date of July 2011 converted to 'July 1 2011' and 'July 31 2011'?
EDIT
I'm only getting a 0 value from InvalidCount but I know I have one record in there as a test. Why isn't it being counted?
MY PROC:
SELECT
(SELECT COUNT(*) FROM dbo.Members m WHERE m.memberID = #pMemberID AND m.SignUpDate BETWEEN #pDate AND DATEADD(MONTH, 1, #pDate)-1) AS 'SignUpDate',
COALESCE(SUM(m.ValidCount), 0) AS ValidCount,
COALESCE(SUM(m.InvalidCount), 0) AS InvalidCount
FROM
dbo.Members m
INNER JOIN
dbo.MemberStats ms ON m.MemberID = ms.MemberID
WHERE
m.SignUpdate BETWEEN #pDate AND DATEADD(MONTH, 1, #pDate)-1
The exact syntax depends on the SQL Engine, but if you start with the 1st of the month, then add 1 month, and finally subtract 1 day; you get the end of the month.
(I'll assume MS SQL Server to match your C# tag)
SELECT
*
FROM
members
WHERE
signupdate BETWEEN #param AND DATEADD(MONTH, 1, #param) - 1
If the between isn't required, you can use DatePart.
Untested example:
where DATEPART(yyyy, SignupDate) = 2011 and DATEPART(m, SignupDate) = 7
convert varchar to appropiate format you want and then compare
check the list of formats. Hope this helps dude.
convert date
Firstly, you must convert the string representation to a valid DateTime struct object on the server. You can use var date = DateTime.ParseExact("july 1 2011", "MMMM dd yyyy", CultureInfo.CurrentUICulture) or DateTime.TryParse. Then you pass this into your SqlCommand as parameters. Never use strings when querying, especially when it comes from user input.

SQL-Date-Question: How to get Yesterdays date in the following formatte

Here is What I have So Far
declare #Today smalldatetime
Set #Today = GETDATE()
select #Today
YIELDS
2011-03-10 13:46:00
What I need IS:
2011-03-09
Try this:
SELECT REPLACE(CONVERT(VARCHAR, DATEADD(dd, -1, GETDATE()), 102), '.', '-')
GETDATE() returns the current date/time.
DATEADD(dd, -1, GETDATE()) substracts one day from the current date/time.
CONVERT(VARCHAR, #DATE, 102) converts the date to ANSI format yyyy.mm.dd
and the REPLACE will replace the periods in the predefined format with hyphens as per your example.
For 2008 you can take advantage of the new DATE datatype:
SELECT CAST(DATEADD(d,-1,GETDATE()) AS DATE) AS Yesterday
For all versions:
SELECT CONVERT(CHAR(10), DATEADD(d,-1,GETDATE()), 120) AS Yesterday
Obviously, the datatype returned by each method is different.
SELECT CONVERT(varchar, DATEADD(d,-1,GETDATE()), 110)
or
SELECT CAST(DATEADD(d,-1,GETDATE()) AS DATE) AS 'DATE'
Good reference if you ever need those codes again.
http://www.w3schools.com/sql/func_convert.asp
SELECT CONVERT(VARCHAR, DATEADD(d,-1,GETDATE()), 110) AS Yesterday

In SQL I would like to subtract a date from a previous row date

The problem is that the dates are stored in the SQL database as nvarchar() and the times are stored in a separate column. I only have read access to this database, so I can't change the format. Besides, it would probably void our support if the manufacturer found out.
As I see I need to first combine the dates and times into one cell as a datetime and then subtract the previous row from the current.
ActualTime, ActualDate
5:30:26, 31-Dec-09
16:01:47, 31-Dec-09
17:35:50, 31-Dec-09
18:31:31, 31-Dec-09
18:51:03, 31-Dec-09
18:55:35, 31-Dec-09
19:26:53, 31-Dec-09
5:25:37, 1-Jan-10
5:38:36, 1-Jan-10
5:46:58, 1-Jan-10
6:27:00, 1-Jan-10
Several people have asked what language I was using. I was hoping to do all of this at the server. On the code side (C#) it's a trivial problem.
Like I said I am looking for an SQL Server server-side solution.
In Microsoft SQL Server, to convert your columns in a date you can
Select Cast( ActualDate + ' ' + ActualTime AS DateTime)
to compare between two dates
Select
Datediff(
second,
Cast('13-dec-2009 ' + '19:39:33' As DateTime),
Cast('13-dec-2009 ' + '19:26:33' As DateTime)
)
More on DATEDIFF (Transact-SQL) parameters.
And to get the difference from the current date/time use the GETDATE(),
Select
*,
oldness = DateDiff(
second,
GETDATE(),
Cast(ActualDate + ' ' + ActualTime AS DateTime)
)
From
your_table
Finally to do it between rows (for the whole table..),
Select *,
Cast(ActualDate + ' ' + ActualTime AS DateTime) as [fulldate],
DiffFromPrevious = Coalesce(
DateDiff(
second,
(
Select Top 1 Cast(ActualDate + ' ' + ActualTime AS DateTime) AS [fulldate]
From yourtable
Where Cast(ActualDate + ' ' + ActualTime AS DateTime) < Cast(t1.ActualDate + ' ' + t1.ActualTime AS DateTime)
Order By [fulldate] Desc
),
Cast(ActualDate + ' ' + ActualTime AS DateTime)
),
0)
From
yourtable t1
Order By
[fulldate] Asc
What language are you using, and what kind of Database is it? I'm not sure if the database has capabilities to do row manipulation within a query (subtracting one row from the other), so you would have to do this programmatically. I'm not sure what language you're using, but if it has a Date or Time API then you can use that to create a Date object. There should a function that returns the total number of seconds since a starting date (January 1, 1970 or something). You create your two Date objects, convert into number of seconds and then subtract them. You can then calculate the number of days between them.
If you're using PHP, I suggest you use the strtotime() function to convert it into a time object. Do this for both dates. The difference will give you the number of seconds between them.

Categories

Resources