Query to check Date in Sql - asp.net

My query is simple yet bit twisted for me. Actually I am working on registration module of an app, where the registration expires 31st March every year. The registration is valid from April 1 to March 31. So whenever a user is registered in between the date, I want his status to be expired if march 31 is crossed.
Let me make more clear to you.
Say I have registered my self in 15Nov2010, then on 31st March 2011, my subscription will get expired. I want to check it automatically as the years will go on. I need a query that will automatically query the created date with expiration date. I am already having a select query and i need to embed this condition and i want to check the creation date with current system date. If Current system date is not 31 march midnight 12, the status must be active else expired.

This can be used for MS SQL to determine whether it has expired or not.
create table #t
(
CreateDate datetime
)
Insert Into #t
select GETDATE() union all
Select DateAdd(month,4, getdate())
Select Case When CreateDate < getdate() And
Getdate() < Cast(str(DatePart(year, getdate())) + '-03-31' as datetime) Then
'Active' Else 'Expired' end as [Status],
CreateDate
From #t
drop table #t
To filter your query you would simply move the case statement to a where clause
e.g.
Where Case When CreateDate < getdate() And
Getdate() < Cast(str(DatePart(year, getdate())) + '-03-31' as datetime) Then
'Active' Else 'Expired' end = 'Expired'

What you need is to schedule a job (i think they're called events on MySql) to run every year on March 31 11:59 and update set the status of all your accounts to expired. (remember to make dstinction on admin accounts) :)
Take a look at this.
for MySQL
http://dev.mysql.com/tech-resources/articles/mysql-events.html#1
for SqlServer
http://msdn.microsoft.com/en-us/library/ms191439.aspx
http://msdn.microsoft.com/en-us/library/ms190268.aspx

I am considering a table YourTable and it has a column Date of type datetime
You can use this query -
select [Date], dbo.GetStatus([Date]) as 'status' from YourTable
And, the function GetStatus -
CREATE FUNCTION [dbo].[GetStatus](#Date datetime)
RETURNS varchar(10)
AS
BEGIN
DECLARE #Return varchar(10)
DECLARE #Year int
SELECT #Year = DATEPART(YYYY,GETDATE())
IF GETDATE() >= CONVERT(datetime,'01-APR-' + CONVERT(varchar,#Year))
SET #Year = #Year + 1
IF #Date BETWEEN CONVERT(datetime,'01-APR-' + CONVERT(varchar,#Year-1)) AND CONVERT(datetime,'31-MAR-' + CONVERT(varchar,#Year))
set #return = 'active'
ELSE
set #return = 'inactive'
Return #return
END;

I'd probably have a "last renewed" column (It would initially store the creation date) then write:
SELECT CASE WHEN
YEAR(DATEADD(mm, -3, LastRenewed)) < (YEAR(GETDATE()) - 1)
THEN 'Active'
ELSE 'Expired' END
AS Status
FROM TableName
I don't see what the problem with #Barry's answer is though, to be honest. If you need to use this logic in several places you can avoid repeating yourself using a view eg:
CREATE VIEW ActiveOrNot AS
SELECT Account, CASE WHEN
YEAR(DATEADD(mm, -3, LastRenewed)) < (YEAR(GETDATE()) - 1)
THEN 'Active'
ELSE 'Expired' END
AS Status
FROM TableName
You could then select only active accounts using:
SELECT Account
FROM ActiveOrNot
WHERE Status = 'Active'

Related

how to return something else when nothing is found?

My current query:
select timestamp from messagesTable
where partner_jid='" + lastUserJid + "' AND msg='.roll'
order by timestamp DESC LIMIT 1 OFFSET 1;
This works fine... unless the values don't exist in the database.
If values do not exist in database, then it should Select * messagesTable; or do nothing if possible.
Is there a way to add a check for that within the same query? It has to be the same query unfortunately because I need to execute things through adb shell. I've been trying things out with CASE but I do not really understand much about SQL.
You can just append a second query, with a WHERE filter that checks whether the first query did not return anything:
SELECT *
FROM (SELECT timestamp
FROM messagesTable
WHERE partner_jid = ?
AND msg = '.roll'
ORDER BY timestamp DESC
LIMIT 1 OFFSET 1)
UNION ALL
SELECT -1 -- or "timestamp FROM msgTab", or whatever
WHERE NOT EXISTS (SELECT timestamp
FROM messagesTable
WHERE partner_jid = ?
AND msg = '.roll');

SQL Server Filtering by DateTime column, when TIME portion is provided sometimes

In an SSRS report, the user searches based on start date and end date.
The challenge is, as I discovered recently, he sometimes, not always, provides the time component while searching.
Currently, the filter is done like this:
if #pEndDate is null
SET #pEndDate = getdate()
SET #PEndDate = DateAdd(dd,1,#PEndDate)
SELECT ........
FROM .....
WHERE ( Createdon >= #PStartDate AND Createdon < #PEndDate)
This is fine when he searches without time (example - #PStartDate = 2/23/2015 and #PEndDate = 2/24/2015)
How should I structure the query to deal with the time portion when he provides it? (example - #PStartDate = 2/23/2015 15:00 and #PEndDate = 2/24/2015 15:00)
If this is answered elsewhere, please point me to it. Thank you.
If you just want to match the date part then there are lot options.
1) You can use the Date type for the parameter PEndDate and PStartDate to nullify the time part
2) You can use the Convert method to get only date part of the parameter while matching.CONVERT (DATE, #PEndDate) OR CONVERT(varchar,#PEndDate,103)
3) Get Date Part only from DateTime using DateTime functions
ATEADD(dd, 0,
DATEDIFF(dd, 0, #PEndDate))
4) Get Date Part only from DateTime using FLOOR and CAST functions
CAST( -- Convert the integer to DATE
FLOOR(-- Get largest Integer less than or equal to the decimal value
CAST(GETDATE() AS DECIMAL(12, 5)) -- Convert DATETIME to DECIMAL)
AS DATETIME) 'Date Part Only'
5) Get Date Part only from DateTime using DATEPART and CONVERT functions
CONVERT(VARCHAR(4),DATEPART(YEAR, #GETDATE))
+ '/'+ CONVERT(VARCHAR(2),DATEPART(MONTH, #GETDATE))
+ '/' + CONVERT(VARCHAR(2),DATEPART(DAY, #GETDATE))
'Date Part Only'
Use whichever method suits you and you find fancy.
UPDATE
As you mentioned you need to get the time part to 00:00 with date so you can try as,
SELECT CAST( convert(varchar(10),GETDATE(),112) AS DATETIME)
--This will give you 2015-02-27 00:00:00.000
SELECT DATEADD(ms,-3, DATEADD(day, DATEDIFF(day,0,GETDATE())+1,0))
--This will give you end of days time 2015-02-27 23:59:59.997
SELECT CONVERT(nvarchar,getdate(),103) + ' 12:59:59 PM'
--This will give you custom time 27/02/2015 12:59:59 PM

Query/return records with dates between Sunday and Saturday?

I've searched this site and others, but couldn't find this exact scenario. I need to add a gridview to my page where the sqldatasource is based on a query that returns records that fall between Sunday and Saturday of the current week. (Each record has one date field) The records are for payroll purposes and the payroll week runs from Sunday to Saturday. I need to find all records that fall in the current pay week. Can anyone point me in the right direction to get started? I'm coding in VB.
This is a SQL question so you should tag it accordingly with your dbms.
Assuming you're using SQL-Server, DATEPART can be used to get the weekday as int of a datetime field and DATENAME can be used to get the name of the weekday.
For example(assuming Sunday to Saturday actually means from Monday to Friday):
SELECT t.*
FROM YourTable t
WHERE DATEPART(weekday, YourDateField) BETWEEN 2 AND 6
Note that it depends on regional settings what is the first day of the week.
Edit: If you want to select records from the current week.
SELECT t.*
FROM YourTable t
WHERE YourDateField >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) / 7 * 7, 0)
AND YourDateField < DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()), 0)
http://msdn.microsoft.com/en-us/library/ms186819.aspx
I suppose you are searching a way to get the working time of an employee between two date
(from sunday to saturday). You need the exact date of Sunday before today.
This could be done via this function
Public Function FirstWeekDay(d as DateTime) As DateTime
While(d.DayOfWeek <> DayOfWeek.Sunday)
d.AddDays(-1)
End While
return d
End Function
The date returned is your startDate while your endDate depends where you want to stop your search.
According to your question this date is the following Saturday. Simply add 6 days to the startDate.
Now it's only a matter to pass the correct parameters to your query/storedprocedure:
SELECT w.* FROM workTime w WHERE w.empID = #empID AND w.workDate BETWEEN #startDate AND #endDate

ASP.Net SQL Where Date is after Today

Hi all I have the following Query made using the Query Builder in Visual Studio.
SELECT Schd_ID, Schd_Date, Schd_Avaliable, Schd_Nights, Schd_Price, Accom_ID
FROM Schedule
WHERE (Schd_Avaliable = 'Yes') AND (Accom_ID = Accom_ID)
I want to add another WHERE statement which adds where Schd_Date is after todays date, any ideas?
Assuming SQL Server, the GETDATE() function returns the date and time the statement was run at:
WHERE Schd_Date > GETDATE()
Use the following for finding dates greater than the current date at midnight:
WHERE Schd_Date > DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
However, CURRENT_TIMESTAMP is the ANSI means of getting the current date and time in a database. Beyond that, date functionality is not consistent between databases so you'd have to tell us what you are dealing with for better answers.
If this is SQL Server you could use the GETDATE() function to return the current date and compare against it:
SELECT
Schd_ID, Schd_Date, Schd_Avaliable, Schd_Nights, Schd_Price, Accom_ID
FROM
Schedule
WHERE
(Schd_Avaliable = 'Yes')
AND
(Accom_ID = Accom_ID)
AND
(Schd_Date > GETDATE())
SELECT Schd_ID, Schd_Date, Schd_Avaliable, Schd_Nights, Schd_Price, Accom_ID
FROM Schedule
WHERE (Schd_Avaliable = 'Yes') AND (Accom_ID = Accom_ID) AND (GETDATE() < Schd_Date)
This should work
I guess this expression can be used as a date representing the current date on the format yyyy-mm-dd (without the hours,minutes and seconds).
(Datepart('yyyy',getdate())+ '-' +Datepart('m',getdate())+ '-' + Datepart('d',getdate()))
therefore
SELECT Schd_ID, Schd_Date, Schd_Avaliable, Schd_Nights, Schd_Price, Accom_ID
FROM Schedule
WHERE (Schd_Avaliable = 'Yes') AND (Accom_ID = Accom_ID) AND
(Schd_Date >= (Datepart('yyyy',getdate())+ '-' +
Datepart('m',getdate())+ '-' +
Datepart('d',getdate())))

SQL Date Search without time

I have a query that searches by date. the dates in the database include the time. How do I search on just the date only.
select *
from weblogs.dbo.vwlogs
where Log_time between #BeginDate and #EndDAte
and (client_user=#UserName or #UserName Is null)
order by Log_time desc
cmd.Parameters.AddWithValue("#BeginDate", txtBeginDate.Text);
cmd.Parameters.AddWithValue("#EndDAte", txtEndDate.Text);
Leave your sql mostly as is and just fix your parameters:
cmd.Parameters.Add("#BeginDate", SqlDbType.DateTime).Value =
DateTime.Parse(txtBeginDate.Text).Date;
cmd.Parameters.Add("#EndDAte", SqlDbType.DateTime).Value =
// add one to make search inclusive
DateTime.Parse(txtEndDate.Text).Date.AddDays(1);
You also want to check to make sure your textboxes are valid datetimes first, but you should get the idea.
The only caveat here is that due to a quirk with the BETWEEN operator it will match the first instant of the next day. So, to fix that we write the query like this:
SELECT *
FROM vwlogs
WHERE Log_time >= #BeginDate AND Log_Time < #EndDate
AND (client_user=#UserName OR #UserName IS NULL)
ORDER BY Log_time DESC
Pay special attention to the comparision operators around the date.
The first thing to do is to remove the times from the dates. If you want to do this in the sql server code you can use something like the code below. I have this as a function on all the databases I work on
cast(floor(cast(#fromdate as float)) as datetime)
The next thing to worry about is the where criteria. You need to make sure you select everything from the start of the from date to the end of the to date. You also need to make sure queries for one day will work which you can do with a date add like this
Where LogTime >= #fromdate and LogTime < DateAdd(dd, 1, #todate)
In SQL round the start and end date to Whole Dates and use >= #BeginDate and very specifically < #EndDAte. The "rounding" process is not very elegant I'm afraid
e.g.
SELECT #BeginDate = DATEADD(Day, DATEDIFF(Day, 0, #BeginDate), 0),
#EndDAte = DATEADD(Day, DATEDIFF(Day, 0, #EndDAte) + 1, 0)
select *
from weblogs.dbo.vwlogs
where Log_time >= #BeginDate
and Log_time < #EndDAte
and (#UserName Is null OR client_user=#UserName)
order by Log_time desc
Note that I've moved "#UserName Is null" first, as there is some evidence that this test will easily pass/fail, and will cause the second more CPU intensive test (client_user=#UserName) to be ignored if the first test is TRUE (may be TommyRot of course ...)
Also, for best performance, you should explicitly name all the columns you need, and not use "SELECT *" (but that may just have been for the purpose of this question)
If you want to change the sql instead,
TRUNC(Log_Time) will reduce every datetime to to that date at midnight.
Make sure that you build your index on the column as TRUNC(Log_TIME) so it's usable.
Another gotcha - truncating your end date will NOT include that date! Consider:
WHERE Log_Time >= #BeginDate AND Log_Time < #EndDate
If #EndDate is truncated it will be midnight and not match anything on that day. You'll need to add a day!
Clean up the dates by adding the following line before your query...
select
#begindate=dateadd(day,datediff(day,0,#begindate),0),
#enddate=dateadd(ms,-3,dateadd(day,datediff(day,0,#enddate),1))
This will floor your begin date to the lowest possible time (00:00:00.000), and ceiling your end date to the highest possible (23:59:59.997). You can then keep your BETWEEN query exactly as it was written.
select *
from weblogs.dbo.vwlogs
where Log_time between #BeginDate and #EndDAte
and (client_user=#UserName or #UserName Is null)
order by Log_time desc
Hope this helps.

Resources