I am storing history data as a date type (2019-10-10) in SQL Server. I would like to check and return to Friday if day is Saturday or Sunday.
There is no data at the weekend. That is why I want to get Friday's data if it's weekend.
I am storing history data as a date type (2019-10-10) in SQL Server. I would like to check and return to Friday if day is Saturday or Sunday.
There is no data at the weekend. That is why I want to get Friday's data if it's weekend.
7条答案
按热度按时间bq3bfh9z1#
( @@DateFirst + DatePart( weekday, SampleDate ) - 1 ) % 7 + 1
will always return an integer from1
to7
with1
corresponding to Sunday regardless of the setting ofDateFirst
orLanguage
.You can use the following code to push weekend dates back to the prior Friday:
u1ehiz5o2#
The safest method is probably to use
format()
for the day of the week:Because format takes a culture argument, this works regardless of settings that might affect the date format or language returned by
datename()
.iugsix8n3#
One option is to use
Choose()
in concert withDateAdd()
ExampleExample
Returns
bkkx9g8r4#
Hope this helps:
Create table for test:
Insert some test values:
Check what are the days in the inserted data
Check the data before update:
Update statement:
Check the data after update:
Demo:
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=358aaefe516da8dd96e1da73ce4d5f38
um6iljoc5#
You need an update as below
ifsvaxew6#
for specific date use this command
so you can check your date as like as this command :
p4rjhz4m7#
Days are equals to the numbers in sql server:
DATEPART(DW, GETDATE())
gives you current day as a number.Use it in IF AND ELSE in ms sql server.
FOR EXAMPLE:
If day is Saturday(6) use minus 1 to get friday.