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

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

Related

SQL Server query to get values between fromdate and todate as well as fromdata, todate

SQL Server query to get values between (from date) to (to date) with from date and to date.
I had tried
select *
from abc
where 1 = 1
and entrydate between '"txt1.Text"' and '"txt2.Text"'
I get result between startdate and enddate but in need values of start date and enddate also
If I had a #StartDate parameter and #EndDate parameter both as Datetimes, I would cast them to dates so you can get:
Select *
From ABC
Where entrydate >= CAST(#StartDate as Date)
and entrydate < DATEADD(d, 1, CAST(#EndDate as Date))
Since the end date would be essentially midnight on the morning of the end date, to include it you have to advance it to the next day, then you can do a less than and the previous day is fully included.

How to convert Persian date into Gregorian date in SQL Server

I have some Persian dates in my sql server table with the following format:
1394/05/14
I have to use stored procedure to convert it into Gregorian date because I need to compare it with today's date.
Does anyone know the solution? I have found some codes but they have problems in leap year and such things.
BTW I have the following code in C# but I think I have to use sql server proc because this proc should be executed with a fixed schedule.
public static DateTime ConvertToGregorianDate(string persianDate)
{
PersianCalendar pcalendar = new PersianCalendar();
int Year = int.Parse(persianDate.Split('/')[0]);
int Month = int.Parse(persianDate.Split('/')[1]);
int Day = int.Parse(persianDate.Split('/')[2]);
return new DateTime(Year, Month, Day, pcalendar);
}
Thanx in advance.
There is a project at GitHub that exactly does what you want! You just need to install its functions in your database by following the provided instructions. Then you can convert dates like below.
The main benefit of this library is that you are totally free to shape the returned result based on your needs. In fact, there is no fixed returned format.
select dbo.JalaliToGregorian('1395/06/11','/')
--returns 2016-09-01 00:00:00.000
select dbo.GregorianToJalali(GETDATE(),'yyyy MMMM dddd')
-- returns 1395 پنج شنبه مهر
select dbo.GregorianToJalali(GETDATE(),'yyyy/MM/dd HH:mm')
-- returns 1395/07/01 15:04
In the above examples suppose that GETDATE() Method in Sql server returns 2016/09/22 15:04:33!
A few different approaches
1) Use SQL CLR to run C# code from within SQL Server
2) Find or write a correct implementation of Persian<->Gregorian conversion in T-SQL
3) Run your C# code for all the dates you care about and dump the output to a file. Import that file into a table. When you need to convert, just look up the answer.
Option (3) is probably going to be the easiest, most maintainable, and best-performing solution. The nice thing about dates is that there really aren't that many of them. A calendar table for a hundred years is just kilobytes of memory, and databases are pretty good at doing lookups.
You can use bellow functions for your purpose (Iranian Calendar to Georgian Calendar) and for more information you can see here:
-- First, we need to convert Persian calendar date to Julian Calendar date
Create FUNCTION [dbo].[UDF_Persian_To_Julian](#iYear int,#iMonth int,#iDay int)
RETURNS bigint
AS
Begin
Declare #PERSIAN_EPOCH as int
Declare #epbase as bigint
Declare #epyear as bigint
Declare #mdays as bigint
Declare #Jofst as Numeric(18,2)
Declare #jdn bigint
Set #PERSIAN_EPOCH=1948321
Set #Jofst=2415020.5
If #iYear>=0
Begin
Set #epbase=#iyear-474
End
Else
Begin
Set #epbase = #iYear - 473
End
set #epyear=474 + (#epbase%2820)
If #iMonth<=7
Begin
Set #mdays=(Convert(bigint,(#iMonth) - 1) * 31)
End
Else
Begin
Set #mdays=(Convert(bigint,(#iMonth) - 1) * 30+6)
End
Set #jdn =Convert(int,#iday) + #mdays+ Cast(((#epyear * 682) - 110) / 2816 as int) + (#epyear - 1) * 365 + Cast(#epbase / 2820 as int) * 1029983 + (#PERSIAN_EPOCH - 1)
RETURN #jdn
End
Go
--Secondly, convert Julian calendar date to Gregorian to achieve the target.
Create FUNCTION [dbo].[UDF_Julian_To_Gregorian] (#jdn bigint)
Returns nvarchar(11)
as
Begin
Declare #Jofst as Numeric(18,2)
Set #Jofst=2415020.5
Return Convert(nvarchar(11),Convert(datetime,(#jdn- #Jofst),113),110)
End
Go
-- Here is the example
Select dbo.[UDF_Julian_To_Gregorian](dbo.[UDF_Persian_To_Julian](1391,1,30))
--Result is 04-18-2012
Another simple conversion is here:
SELECT FORMAT(sysdatetimeoffset() at time zone 'Iran Standard Time' , 'yyyy/MM/dd-HH:mm:ss', 'fa')
I hope you found this useful.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: MohammadSoori
-- Create date: 2021-06-21
-- Description: Convert Persian date to Miladi date.
-- =============================================
-- SELECT [dbo].[PersianToMiladi] ('1400/01/01')
-- =============================================
CREATE FUNCTION [dbo].[PersianToMiladi]
(
#PersianDate VARCHAR(10)
)
RETURNS DATE
AS
BEGIN
SET #PersianDate = RIGHT (#PersianDate, 9)
DECLARE #Year INT = SUBSTRING(#PersianDate, 1, 3)
DECLARE #Month INT = SUBSTRING(#PersianDate, 5, 2)
DECLARE #Day INT = SUBSTRING(#PersianDate, 8, 2)
DECLARE #DiffYear INT = #Year - 350
DECLARE #Days INT = #DiffYear * 365.24 +
CASE WHEN #Month < 7 THEN (#Month - 1) * 31
ELSE 186 + (#Month - 7) * 30 END + #Day
DECLARE #StartDate DATETIME = '03/21/1971'
DECLARE #ResultDate DATE = #StartDate + #Days
RETURN CONVERT(DATE, #ResultDate)
END

Sql query with the current date

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)

sql query problem

i want to compare two date and time with each other and
i want to select records that "StartTime" is greater than now time and the "StartDate" is greater than now date.
but output is not correct.thanks in advance.
my tabale'records are:
StartDate StartTime
-------------------------------
1389/07/11 11:04
1389/06/23 21:17
1389/06/23 21:32
1389/06/23 22:10
1389/06/26 12:34
1389/06/27 17:29
1389/06/27 18:13
1389/06/27 20:27
1389/06/28 09:41
1389/07/18 10:46
1389/07/05 22:00
1389/07/15 24:00
output is:
when the query is : (1)
SELECT StartDate, StartTime
FROM Proj
WHERE (StartDate < '1389/07/15 ') AND (StartTime <= '20:20 ')
StartDate StartTime
-------------------------------
1389/07/11 11:04
1389/06/26 12:34
1389/06/28 09:41
1389/07/18 10:46
output is:
when the query is: (2)
SELECT StartDate, StartTime
FROM Proj
WHERE (StartDate > '1389/07/15 ') AND (StartTime >= '20:20 ')
StartDate StartTime
-------------------------------
NULL NULL
the correct output should be:
StartDate StartTime
-------------------------------
1389/07/18 10:46
i use persian date.
Just taking what you have above and the description of your problem, the query should be:
select * from test where date>'2010/10/05' and time>='20:22'
If you post more details about your problem and the schema in which you're working we'll be able to help you more.
I want to select records that "time" is greater than now time and the "date" is greater than now date.
First off to get the current datetime (your now), you can use the SQL function GETDATE().
So if you happen to have a datetime column you could just do
SELECT * FROM Test WHERE LogDateTime >= GETDATE()
This will return every record in the table Test of which the datetime value inside the LogDateTime column is in the future.
Now, although it's a little bit more complicated, the same can be used when you have split the date and the time into separate columns.
SELECT * FROM Test
WHERE CONVERT(datetime, LogDate + ' ' + LogTime) >= GETDATE()
If LogDate or LogTime are nullable columns you could use ISNULL(<columnName>, <defaultvalue>) to be safe.
it solved:
SELECT StartDate, StartTime
FROM Proj
WHERE (StartTime < '20:20 ') AND (StartDate = '1389/07/15') OR
(StartDate > '1389/07/15')

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