varchar vs datetime in sql - sql

I was having problem in retrieving from SQL Server so I posted this [question][1]
I did not get any suitable answers. So I have changed the column datatype from datetime to varchar and now it works fine.
SELECT *
FROM test
WHERE (timeStamp BETWEEN '05-09-2013 18:23:57' AND '05-09-2013 18:23:59')
But my query if varchar datatype can play the role of datetime and in varchar we can also store the string then why sql provides datetime datatype? I know varchar occupies more space than datetime. I would like to know other reasons.

Change datatype of your column to datetime. You can do your query IF you'll use datetime instead of varchar in where clause:
select *
from test
where timeStamp between convert(datetime, '2013-09-05 18:23:57', 120) and convert(datetime, '2013-09-05 18:23:59', 120)
I'm pretty sure it would work even with implicit cast if you use ISO format of date:
select *
from test
where timeStamp between '2013-09-05 18:23:57' and '2013-09-05 18:23:59'
Here's more info about cast and convert.

Another reason apart from space is this:
Datetime has other functions like picking up the day, year, month,hours,minutes,seconds etc so that you don't have to write it for yourself. If you use varchar then it will be your responsibility to provide functions for future use. You should use split function to retrive the part of date you want.
Another is that a query on a varchar works slower when compared to Datetime when you use to conditions to compare month / day/ year

Always use proper DATETIME datatype to store date and time values. Refer this for more information
http://beyondrelational.com/modules/2/blogs/70/posts/10902/understanding-datetime-column-part-iv.aspx

Related

SQL How to format M/DD/YYYY (1/31/1960) to DD/MM/YYYY (31/01/1969)

I have a column that has date and time mixed together i.e. 1/31/1960 12:00:00AM and I would like to convert them into two-column through SQL function:
(a) DD/MM/YYYY i.e 31/01/1969
(b) HH:MM i.e 12:00
Thanks in advance.
Take a look at the CONVERT() function, specifically the style for datetime. Additionally, we can CAST() the DATETIME as a TIME data type to extract the time.
Assuming your original column is a DATETIME data type, you can run
SELECT
CONVERT(NVARCHAR(24),{DateField},103)
,CAST({DateField} AS TIME)
If it is string, you can cast it then convert
SELECT
CONVERT(NVARCHAR(24),CAST('1960-01-31' AS DATETIME),103) AS ReportingDate
,CAST(CAST('1960-01-31' AS DATETIME) AS TIME) AS ReportingTime
If you're on a sufficiently recent version of SQL Server, the FORMAT() function is your friend.
DECLARE #d DATE = GETDATE();
SELECT FORMAT(#d, 'dd/MM/yyyy');
Note, that second argument is a .NET formatting string, so you should be able to use whatever is available from the Framework.

Concatenate Date and Time as DATETIME in SQL Server

I'm having a trouble in combining date and time to DATETIME. I have an existing table with data so I can't change it to Datetime2.
DECLARE #t1 TABLE(StartDate DATE, StartTime Time)
INSERT INTO #t1
VALUES('2018-02-28','08:00:00')
SELECT
CAST(CONCAT(StartDate, ' ', StartTime) AS DATETIME)
FROM #t1
The error shown is:
Conversion failed when converting date and/or time from character string.
Don't concat(). Just add but they both need to be datetime:
select cast(startdate as datetime) + cast(starttime as datetime)
The cast fails because the time component of the datetime data type has less precision than the time data type, as described on this page, which is a useful reference for the various date and time types offered by SQL Server. As you can also see on that page, SQL Server has a datetime2 data type that offers greater precision; if you had used that in your cast, I don't think you would have had a problem.
Gordon's solution is a good one in that it avoids the need to deal with conversions to and from strings in the first place. Just be aware that combining a date and time into a datetime may involve a loss of precision. See this question on the Stack Exchange DBA site for a solution with datetime2 that retains the precision of the original values.

I want to convert a whole column into the date format of yyyymmdd, I do not want the current date

I want to convert a whole column into the date format of yyyymmdd, I do not want the current date, thus I cannot use getdate() command, there is already data in the column, I just need the right command to convert the whole column into yyyymmdd format.
The column I am using is FIELD_034 and the table is Sur_CompassAuto1_1_7_fetch.
I am using SQL Server.
Thank you
I fully agree with the paqogomez's response, but instead of date style of 111, better use 112.
The output for the statement
SELECT CONVERT(VARCHAR(10), FIELD_034, 111)
will result in yyyy/MM/dd. Where as,
SELECT CONVERT(VARCHAR(10), FIELD_034, 112)
will return yyyyMMdd, which is what he needed.
A common misconception is that a datetime has a format. If you are storing your dates as a datetime, then you can output it in any format.
It sounds as though you might be storing your values as a Varchar. You would be better off converting your varchar dates into a datetime, then you can do whatever you want with them
That said, if you HAVE FIELD_034 as a DateTime, then its as easy as
SELECT CONVERT(VARCHAR(10), FIELD_034, 112)
from Sur_CompassAuto1_1_7_fetch
If the field is a varchar its similar:
SELECT CONVERT(datetime, FIELD_034, 112)
from Sur_CompassAuto1_1_7_fetch
The difficulty of this one is if you have your values in different or nonstandard formats. Then it would require some clean up to make the query work.
Edit: as #AArnold says, its 112 instead of 111. Date formats are subtle.

Return date only (not time)

I have a column that stores date information as a varchar(8). All of the data is entered as yyyymmdd. I would like to cast this information in a view to display as a date. When I try:
SELECT CAST(HIRE_DATE AS datetime)
The values are returned with the time. For example a record that has 19951107 casts as 1995-11-07 00:00:00.000.
How can I have it just return "1995-11-07" without the time value?
This would seem to be what you're looking for:
SELECT CONVERT(VARCHAR, CAST(HIRE_DATE AS DATETIME), 102)
Note that the return value is VARCHAR, not a true DATE, DATETIME, etc.
If you need it as a DATETIME datatype then omit the CONVERT.
SELECT CAST(HIRE_DATE AS DATETIME)
CAST and CONVERT should be helpful.
The answer from #DMason (cast(HIRE_DATE as datetime)) is the correct one if you have SQL Server 2005 or earlier.
SQL Server 2008 introduced the date datatype which means you can achieve what you want with cast(HIRE_DATE AS date).
If there are invalid dates in your varchar(8) column then cast() will cause the query the fail. SQL Server 2012 introduced the try_ conversion functions which return a null marker if the cast is impossible. So, you can achieve what you want with try_cast(HIRE_DATE AS date).
From Books Online: Conversion functions.

How do I strip the date off of a datetime string in SQL SSIS?

I'm working on a data warehouse project and would like to know how to (preferably in a Derived Column component in a Data flow) strip the date piece off of a SQL datetime record.
Once I have the datetime converted to just a time I am going to do a lookup on the time to find the related time record in a time dimension table.
Can someone give me a simple function to accomplish this inside a derived column transform?
Example: Transform a datetime such as "12/02/2008 11:32:21 AM" into simply "11:32:21 AM".
I would just do a cast to DT_DBTIME type (using Derived Column transform, or Convert type transform). DT_DBTIME contains just (hours, minutes, seconds) part of the date/time, so you'll get rid of the date part.
If you need to do this in a variable expression Michael's solution won't work, but you can use the following expression:
(DT_DATE)(DT_DBDATE)GETDATE()
(DT_DBDATE) converts the current date and time to a date only. But the new datatype is not compatiple with SSIS's datetime. Therefore you'll have to use (DT_DATE) for converting to a compatible type.
Courtesy of this solution belongs to Russel Loski who has posted it in his blog:
http://www.bidn.com/blogs/RussLoski/ssas/1458/converting-datetime-to-date-in-ssis
Actually if you reverse the first 2 expressions like this: (DT_DBDATE)(DT_DATE)GETDATE()
instead of (DT_DATE)(DT_DBDATE)GETDATE(), then you will TRUNCATE the time off the date field.
If the DT_DATE expression is before the DT_DBDATE expression, you will still have the time portion in your output, but it will be reset to all zeroes.
Ran into this with writing a report for a scheduling app, needed the time that was stored as part of a datetime data type. I formated the datetime as 0 which gives you this mon dd yyyy hh:miAM (or PM), and just did a substring of that which returned the time only in an AM/PM format.
Example below.
DECLARE #S DATETIME = GETDATE()
SELECT SUBSTRING(CONVERT(NVARCHAR(30), #S , 0) , 13 , 10) AS ApptTime
, CONVERT(NVARCHAR(30), #S , 0) AS ApptDate
I personally use a series of functions for this. E.g.:
ALTER FUNCTION [dbo].[TIMEVALUE]
(
#Datetime datetime
)
RETURNS datetime
AS
BEGIN
RETURN (#Datetime - CAST(ROUND(CAST(#Datetime AS float), 0, 1) AS datetime))
END
I'd love to claim all the credit but it should really go to this guy.