Find rows that have yesterdays date -- Invalid column? [duplicate] - sql

This question already has answers here:
How to use alias column name in where clause in SQL Server
(5 answers)
Using new columns in the "where" clause
(5 answers)
Closed 20 days ago.
Goal: I am trying to get the rows in a table that have yesterdays date (but the original column is in datetime).
What I've tried:
I was able to figure out how to get yesterdays date from https://learnsql.com/cookbook/how-to-get-yesterdays-date-in-t-sql/
But I also had to cast the DateTime from the table to date to match that yesterdays date was in Date format. So the SO articles like SQL statement to select all rows from previous day did not work.
When I try to find the matching rows from my DB Table, it says:
Invalid column name 'YesterdayDate'
SQL:
SELECT cast(DateEnded as date) AS YesterdayDate
FROM [dbo].[V]
WHERE YesterdayDate = DATEADD(DAY, -1, CAST(GETDATE() AS date));
How can I correctly do this?

In fact don't do it that way. You want to avoid calling functions on columns in your WHERE clause as they can make the query unsargable i.e. unable to use indexes. Instead use the actual column, and rather than converting to a date use a datetime window of the previous day.
SELECT CAST(DateEnded AS date) AS YesterdayDate
FROM [dbo].[V]
WHERE DateEnded >= DATEADD(DAY, -1, CAST(GETDATE() AS date))
AND DateEnded < CAST(GETDATE() AS date);

Related

check age based on Date of Birth in SQL Server [duplicate]

This question already has answers here:
How to calculate age (in years) based on Date of Birth and getDate()
(40 answers)
Closed 8 months ago.
I am trying to check the Age of a user from the Date Of Birth to make sure Age is between 16 and 80, When the data is inserted into the table
The Date of Birth is a DATE datatype
I have tired looked for multiple solutions and none of them check it when the data is inserted
I have found this help out article to get the current Date with only the Date: https://learnsql.com/cookbook/how-to-get-the-current-date-without-time-in-t-sql/#:~:text=To%20get%20the%20current%20date%20and%20time%20in%20SQL%20Server,20%2010%3A22%3A34%20.
But i can't seem to get it to work with the CHECK function when creating the table
The other answer does not correctly deal with partial years.
For example, given GETDATE() as 20220626 and a DateOfBirth as 20060627, a calculation based on DATEDIFF will return TRUE. This is because DATEDIFF just counts the number of date boundaries that pass between the two dates.
Another issue is that it cannot use indexes.
A more correct caluclation uses DATEADD against the current date:
WHERE DateOfBirth <= DATEADD(year, -16, CAST(GETDATE() AS date))
AND DateOfBirth > DATEADD(year, -80, CAST(GETDATE() AS date));
You also need CAST AS date otherwise you end up with conversion issues
db<>fiddle
Something like:
DATEDIFF(year, DateOfBirth, GETDATE()) BETWEEN 16 AND 80
Not final code, but could be inserted in your scenario hopefully :)

SQL Server: Inconsistencies in date

create table #temp
(
A date
)
insert into #temp(A)
values(GETDATE())
insert into #temp(A)
values(GETDATE()-1)
Now when I query the table as
select A from #temp where A>=GETDATE() and A<=GETDATE()
I get no records
But GETDATE() record value should satisfy my where condition, shouldn't it at least pass me one record?
Please guide me if I am missing some point here.
You need to do conversion, so it seems :
where a >= convert(date, dateadd(day, -1, getdate())) and
a <= convert(date, getdate());
Your where clause comparing date as :
where a >= '2020-04-21 16:01:27.277' and a <= '2020-04-21 16:01:27.277'
So, you need to convert date because getdate()will also return time portions.
Since your where clause looks for single day so you can do :
where a = convert(date, getdate())
Yogesh is right.
GETDATE() gives the present DATEIME value. When you insert it into a DATE column, SQL Server coerces -- silently typecasts -- the DATETIME to a DATE before inserting it.
But when you use it in a WHERE clause, SQL Server coerces the DATE from your column into a DATETIME value by turning 2020-04-20 into 2020-04-20 00:00:00. That can't be the same as GETDATE() except during the first few milliseconds of each day. (Meaning you or your test krewe are extremely unlikely to catch it equal.)

SQL Server : Comparing Time

I am trying to compare time in my SQL query. However, when I run the query, I get zero result but I can see that in the table, there are records that should appear.
The query is as such:
SELECT *
FROM dbo.Alarms
WHERE StartDate <= '26/08/2015'
AND StartTime <= CONVERT(varchar(5), GETDATE(), 108)
The StartDate is stored in the database as YYYY-MM-DD and it seems to work fine when I query only with the date.
However, when I add the StartTime is when things don't work. StartTime stores the value in the 24 hour clock format.
What am not doing right?
Thanks
Use a correct datetime format:
SELECT *
FROM dbo.Alarms
WHERE StartDate <= '2015-08-26' AND StartTime <= cast(GETDATE() as date)
Don't compare date/time values as strings. The data types are built into the language. Use them.
I have not explicitly used this scenario but comparing dates can be a problem depending on how the fields are compared.
eg: '28/07/2015' is not less than your startdate as 28 > 26.
You could try comparing dates reformatted into a YYYYMMDD format.
Cheers.

How to cast GETDATE() to be only time ignore day,month and year [duplicate]

This question already has answers here:
Compare time part of DateTime data type in SQL Server 2005
(6 answers)
Closed 4 years ago.
I have a table for store takt-time. It's compound with "day_shift(1)" and "night_shift(0)" like below.
If I put current time(by using GETDATE() function ).
I need to know this current time is "day(1)" or "night(0)". my query like this.
SELECT [day_shift_flag]
FROM [company_working_time]
WHERE GETDATE() BETWEEN [start_time] AND[end_time]
But it can't found because a date received from GETDATE() isn't '1900-01-01'
How to compare a only time and ignore day,month,year.
What should I do?
You can cast a DateTime as a Time data type. For example:
SELECT
[day_shift_flag]
FROM [company_working_time]
WHERE
CAST(GETDATE() AS TIME) BETWEEN CAST([start_time] AS TIME) AND CAST([end_time] AS TIME)
By Following Way You can Ignore the day,month,year
SELECT [day_shift_flag]
FROM [company_working_time]
WHERE DatePart(HH,GETDATE()) BETWEEN DatePart(HH,[start_time]) AND DatePart(HH,[end_time])

query to select data from this day [duplicate]

This question already has answers here:
In SQL Server, what is the best way to filter items for an entire day
(3 answers)
Closed 8 years ago.
I have a database table that has Datelogged columns from type Datetime (Sql server 2008 r2)
The Datelogged value is like this 2014-10-22 12:57:36.583
I want to do a query to select all the rows that its date is today (I care about year, month, and day) but not (hour, second.)
This is my query
string query = "SELECT * FROM Orders WHERE PrintTime is NULL WHERE Datelogged = #Datelogged";
but I didn't know what should I do to tell the query to compare just on year-month-day
Based on #Aaron Bertrand comment
It appears that it is better to use a Date Range from current day midnight (00:00:00) to < tomorrow at midnight.
Query copied from his comment.
DateLogged >= CONVERT(DATE, #DateLogged) AND
DateLogged < DATEADD(DAY, 1, CONVERT(DATE, #DateLogged))
Also see: Bad habits to kick : mis-handling date / range queries By Aaron Bertrand
(Old Answer)
You can use CONVERT(DATE, Datelogged) to get Date part without time.
"SELECT * FROM Orders WHERE PrintTime is NULL AND CONVERT(DATE, Datelogged) = #Datelogged"
Make sure you pass the parameter value using Date property in C# like:
cmd.Paramaters.AddWithValue("#Datelogged", DateTime.Today);// or DateTime.Now.Date
Also make sure to remove multiple WHERE from your query and use AND or OR to combine two conditions depending on your requirement.
Get the minimum date time range for current date and maximum date time range for today. Then, compare it with the logged date value.
Conversion operator on any table column adds extra conversion overhead and leads to inefficient use of index. Should be avoided when possible.
SELECT * FROM Orders
WHERE PrintTime is NULL
AND (Datelogged > dateadd(DD, -1, cast( GETDATE() as date)) AND Datelogged < dateadd(DD, 1, cast( GETDATE() as date)));