Convert date to day of week into SQL Server - sql-server

I would like to convert a SQL query in MS Access into SQL Server. This query is about converting date into day of week. Please advise.
MS Access:
UPDATE Contact_Hist
SET WK_DAY = weekdayname(weekday(cdate(mid(date_id,5,2) & "/" & right(date_id,2) & "/" & left(date_id,4))));
For instance, DATE_ID = 20140703 as per the table (Contact_Hist) and would like to convert to the day of week i.e. 'Thursday'.

You should use SQL Server's DatePart() function:
DatePart(weekday, Cast('20140703' AS date))
This will return an integer between 1 (Monday) and 7 (Sunday) inclusive.
<edit2>
How the DatePart() return value [integer] is interpreted is determined by SQL Server's SET DATEFIRST setting (or default configuration). That is, whether a returned 1 is Monday, 2 is Monday, and so on.
</edit2>
<edit>
To get the name of the day of the week use the DateName() function.
DateName(weekday, Cast('20140703' AS date))
For reference purposes, both DatePart() and DateName() take a "date" (that is, a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value) as the 2nd parameter. SQL Server will implicitly convert a date string into a date, so the CAST('20140703' AS date) is not required.
</edit>

In MS SQL Server 2012, you can do the following and get "Friday" back:
SELECT DATENAME ( weekday , '20140704' )
as demonstrated by this SQLFiddle: http://sqlfiddle.com/#!6/fc24a/8
So do:
UPDATE Contact_Hist SET WK_DAY = DATENAME ( weekday , date_id )

Related

Convert IIF() and datepart Access statement to SQL Server

I have a query that pulls some information a given week and it should be on a week day hence the datepart portion. can't get this command to pull into SQL correctly.
IIf(DatePart('w',Date())=2,Date()-3,Date()-1) And Date()))
The above is from the SQL view of access.
dateadd(day,
case datepart(weekday, getdate())
when 2 then -3 else -1 end, /* assumes datefirst is 7 */
cast(getdate() as date)
)

How to find difference in days from DD-MM-YYYY formatted dates in SQL Server?

I want to find the difference between two dates in DD-MM-YYYY format. For example, I have 2 dates 29-10-2018 and 29-11-2018. I want to find the difference in number of days between those two dates (30 days) in SQL Server.
You can change the date format of current session and then use DateDiff function.
SET DATEFORMAT 'dmy'
SELECT DATEDIFF(DAY, '29-10-2018', '29-11-2018')
I will check more about Set DateFormat before adding this to Production code.
That changes the SESSION date format, not the DATABASE.
[Note from Previous Post: This is often not the way to solve the problem of interpreting dates. Datetimes should not be stored a strings if you can avoid it (use a datetime or date column instead). If you have to store in a string form, use an ISO 8601 format which is basically of the form YYYYMMDD]
Use DATEDIFF
SELECT DATEDIFF(day, '2018-10-29 00:00:00.000', '2010-11-29 00:00:00.000')
declare #date1 varchar(10),#date2 varchar(10)
set #date1 = '01-11-2018'
set #date2 = '28-11-2018'
select
datefromparts(
right(left(#date2 ,10),4),
substring(left(#date2 ,10),4,2),
left(left(#date2 ,10),2)
)
select
DATEDIFF
(
DAY,
datefromparts( right(left(#date1 ,10),4),
substring(left(#date1 ,10),4,2),
left(left(#date1 ,10),2)
),
datefromparts( right(left(#date2 ,10),4),
substring(left(#date2 ,10),4,2),
left(left(#date2 ,10),2)
)
)

The data types date and datetime are incompatible in the add operator

I recently created in a SQL Server 2008 dev environment a function that concatenates a date and time like this
select cast('2016-11-09 15:35:00' AS DATE) + CAST('00:00:00' AS DATETIME)
In SQL Server 2008 it works well but deployed in SQL Server 2016 it throws an error
The data types date and datetime are incompatible in the add operator.
But it works well ONLY if queries are placed separately
select cast('2016-11-09 15:35:00' AS DATE)
select CAST('00:00:00' AS DATETIME)
So, how can I fix this. I found articles where people say that there is an incompatibility with TIME data type, but I am not using it. In fact, my concatenation is like this
WHERE
CREATIONDATE BETWEEN CAST(#CurrentDate AS DATE) + CAST('00:00:00' AS DATETIME) AND CAST(#CurrentDate AS DATE) + CAST('23:59:59' AS DATETIME)
where #CurrentDate is a DateTime variable and passed to my function as '2016-11-09 15:35:00'
I cannot modify the configuration of the SQL Server 2016 box. How can I fix my code?
Thanks
Just cast it as a date and then a datetime.
select cast(cast('2016-11-09 15:35:00' as date) as datetime)
To get 1 more day, use:
dateadd select dateadd(dd,1,cast(cast('2016-11-09 15:35:00' as date) as datetime))
I'm not a huge fan of the between operator so when i deal with datetimes i tend to use > startDate and < endDate where the endDate is the next day , so 11/10 which is like saying <= 11/09 23:59:59

Excel incorrectly converts Date into Int

I'm pulling the data from SQL database. I have a couple columns with date which need to be converted into Int type, but when I do this the date changes (-2 days). I tried Cast and Convert and it's always the same.
Converting to other type works fine and returns the correct date, but doesn't work for me. I need only the date part from datetime and it needs to be recognised as a date by Excel.
Why is this happening? Any ideas how to get it sorted?
I'm using the following query:
SELECT wotype3, CONVERT(INT,wo_date2 ,103), CAST(duedate AS int) FROM Tasks WHERE
duedate > DATEADD(DAY,1, GETDATE())
AND wo_date2>0
AND wo_date2<DATEADD(WEEK,3,GETDATE())
ORDER BY wotype3
I've had big problems with this, checking my SQL Server's calculation results with "expected results" which a user had created using Excel.
We had discrepancies just because of this 2-day date difference.
Why does it happen ?
Two reasons:
SQL Server uses a zero-based date count from Jan 1 1900, but Excel uses a 1-based date count from Jan 1 1900.
Excel has a bug in it (gasp!) which makes it think that the year 1900 was a leap year. It wasn't. SQL Server correctly refuses to let you have a date value containing "29-Feb-1900".
Combine these two discrepancies, and this is why all dates, from March 1 1900 onwards, are always 2-days out.
Apparently, this Excel bug is a known issue, to keep it in line with Lotus 1-2-3.
The Intentional Date Bug
Microsoft's own explanation
From now on, I think I'll justify bugs in my code with the same excuse.
;-)
For SQL Server 2008 and above, you can use the DATE datatype.
declare #dt datetime = '12/24/2013 10:45 PM' -- some date for example
SELECT #dt as OriginalDateTime, CAST(#dt as DATE) as OnlyDate
For versions prior to SQL Server 2008, you would need to truncate the time part using one or the other functions. Here is one way to do that:
declare #dt datetime = '12/24/2013 10:45 PM' -- some date for example
SELECT #dt as OriginalDateTime, CAST(FLOOR(CAST(#dt AS FLOAT)) as DATETIME) as OnlyDate

Convert a SQL Server datetime to a shorter date format

I have a datetime column in SQL Server that gives me data like this 10/27/2010 12:57:49 pm and I want to query this column but just have SQL Server return the day month and year - eg. 2010 10 27 or something like that.
What are the functions I should be researching?
Should I be trying to convert to another date data type? Or simply convert it to a string?
Have a look at CONVERT. The 3rd parameter is the date time style you want to convert to.
e.g.
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) -- dd/MM/yyyy format
Try this:
print cast(getdate() as date )
If you need the result in a date format you can use:
Select Convert(DateTime, Convert(VarChar, GetDate(), 101))
In addition to CAST and CONVERT, if you are using Sql Server 2008, you can convert to a date type (or use that type to start with), and then optionally convert again to a varchar:
declare #myDate date
set #myDate = getdate()
print cast(#myDate as varchar(10))
output:
2012-01-17
If you have a datetime field that gives the results like this 2018-03-30 08:43:28.177
Proposed: and you want to change the datetime to date to appear like 2018-03-30
cast(YourDateField as Date)
With SQL Server 2005, I would use this:
select replace(convert(char(10),getdate(),102),'.',' ')
Results: 2015 03 05
The shortest date format of mm/dd/yy can be obtained with:
Select Convert(varchar(8),getdate(),1)
Just add date keyword.
E.g. select date(orderdate),count(1) from orders where orderdate > '2014-10-01' group by date(orderdate);
orderdate is in date time.
This query will show the orders for that date rather than datetime.
Date keyword applied on a datetime column will change it to short date.
For any versions of SQL Server: dateadd(dd, datediff(dd, 0, getdate()), 0)
The original DateTime field : [_Date_Time]
The converted to Shortdate : 'Short_Date'
CONVERT(date, [_Date_Time]) AS 'Short_Date'

Resources