T-SQL Dates using Convert() function? - sql

I am bit confusing here?
declare #date1 datetime = '2016-01-21 14:10:47.183'
I want to convert '2016-01-21 14:10:47.183' To '21-01-2016'
when I tried: select convert(date,#date1,105)
I am getting: 2016-01-21
But with: select convert(varchar(10),#date1,105)
I am getting: 21-01-2016
Why I am not having same results with above code?
Why should I convert to varchar?
Thanks in advance

This is just presentation matter and should be done in application layer. If you cannot do it in application you could use FORMAT (SQL Server 2012+):
declare #date1 datetime = '2016-01-21 14:10:47.183'
SELECT FORMAT(#date1, 'dd-mm-yyyy');
LiveDemo
Why I am not having same results with above code?
select convert(date,#date1,105)
-- DATETIME -> DATE
-- vs
select convert(varchar(10),#date1,105)
-- DATETIME -> VARCHAR(10) using specific style
If you only to skip time part use SELECT CAST(#date1 AS DATE) and do not bother how it is presented. It is still DATE.
To sum up: in SQL query use DATE as date, in application display it with desired format.

The reason why is because once you put a value in a datetime column (or date or any of the other variations on date-time datatypes) in SQL Server. SQL Server ceases to think of that date as having any particular format. It translates it into numbers, and stores it that way internally.
So when you select a date from a date time column, SQL Server displays it in the default format that you have selected based on your environment/local settings.
If you want to display it in any other format, you have to first convert it to a string, because as far as SQL Server is concerned, dates don't have formats. They are just numbers. The 21st day of March is the 21st day of March, whether you write it as 3/21 or 21/3.
So when you try to convert a date to a date with a different format, SQL Server just ignores you because dates don't have formats. However, if you want to convert that date to a string, SQL Server will be happy to help you display that string in any format you like.
Hope this helps, but sounds like some further research into how SQL Server stores dates would help your understanding.

Related

String to datetime conversion in sql server

Is it possible to convert 'OCT-20' to '2020/10/01' in sql server. I tried the following cases without any luck.
select convert(date, 'OCT-20',103)
----Conversion failed when converting date and/or time from character string.
alter table MyTable alter column [period] date
----Conversion failed when converting date and/or time from character string.
I am using sql server 2016.
If we assume that the value is always in the format MMM-yy then you could do this:
SELECT CONVERT(date,'01-' + StringDate,106)
FROM dbo.YourTable;
Of course, this has 2 flaws.
The date uses a 2 digit year, so SQL Server could assume the wrong century
It'll only work if the LOGIN is using an English based language, otherwise it'll fail.
The real solution is to fix your design; never store date (and time) values in a varchar, and when ever you do use a varchar for a date (such as a literal in a WHERE) use an unambiguous format such as yyyyMMdd or yyyy-MM-ddThh:mm:ss.nnnnnnn.

Optional field for DateTime in SQL Server 2019?

I am wondering if it is possible to make Day field optional for any of the Date data types in SQL Server 2019?
For example the user may enter a date in mm-yyyy format e.g. 10-1980 or dd-mm-yyyy format e.g. 25-10-1980.
1. Is it possible for smalldatetime, datetime, date, datetime2 or datetimeofset data types of SQL Server?
2. If not, I think the only option is to store these values via nvarchar data types?
I would suggest storing the results for the month as the first of the month. An easy way to do this is:
select try_convert(date, right('01-' + #date, 10), 105)
The '01-' would be the first day of the month.
If you actually need to distinguish MM-YYYY and DD-MM-YYYY inputs, then you will need to use a string.

Convert TEXT to Date in SQL Server 2012

I have a TEXT in this format 31/10/15.
How do I convert this into a DATE format?
As I need to let the user search from data using a date range.
example: From 15/7/13 to 31/10/15
Or is there a way to so without converting to date?
You can use CONVERT() for this:
DECLARE #d VARCHAR(50) = '31/10/50'
SELECT CONVERT(DATE, #d,3)
Note that with a 2-digit year SQL Server will make the year start with '19' for 50 and up, and 49 and below will be '20'
Storing as a DATE field will allow easier comparisons, otherwise you'll have to perform this conversion at each step.
Use CONVERT; example:
SELECT [Date] = CONVERT(date, '31/10/15', 3);
And yes, it's possible to search dates in the same format as the examples you provide, but don't do that – use the proper data types in both your queries and your table columns.

Select most recent records by DB2 date in form of YYYYMMDD

I am importing records from a DB2 data source into a MS SQL Server destination.
The records are coming in with the date format of 20150302/YYYYMMDD, but I only want the last 14 days based on current server date.
Can some advise on how to select based on this date format against DATEADD(d, - 1, { fn CURDATE() }) please.
Thanks!
It would be better to do this on the DB2 side, to reduce the number of records brought over.
Additionally, it's better from a performance standpoint to convert the static date into a numeric date and compare to the column in your table. Rather than convert the numeric date in your table to a actual date type for comparison.
where numdate >= int(replace(char(current_date - 14 days,iso),'-',''))
Doing it this way will allow you to take advantage of an index over numdate. In addition, DB2 will only need to perform this conversion once.
Depending on your platform & version, you may have an easier way to convert from a date data type to a numeric date. But the above works on DB2 for i and should work on most (all?) DB2 versions and platforms.
You may find it worthwhile to create a UDF to do this conversion for you.
If you want logic in SQL Server, then you are in luck, because you can just convert the YYYYMMDD format to a date:
where cast(datecol as date) >= cast(getdate() - 14 as date)
(This assumes no future dates.)
If you want to do this on the DB2 side, you can use to_date():
where to_date(datecol, 'YYYYMMDD') >= current date - 14 days

How do I store just a date in MS SQL from VB?

My project requires I use VB (5 or 6)* to store a date in an SQL Server database. The SQL datetime type includes the time, which I don't want. I'm also aware that VB's representation of a date doesn't mirror that of SQL Server.
So, how can I store a date held in VB's date type in the SQL database, as the datetime at midnight on that date, for example?
Edit: I need to use the date to select rows further down the line, so I can't get away with just truncating it on read.
*I know, I you were me, you wouldn't start from here. But given the constraints, any VB6/MS SQL fiends out there?
VB6 has a DateValue() function which returns the date portion of a Date/Time value, with the time portion "zeroed out". (Note: When the time portion of a date/time variable is "zeroed out", the time would be interpreted as 12:00 AM.)
SQL Server 2008 has new date and time data types. There is the "Date" data type if you don't want to store the time component.
Use the DateTime column and just truncate the time at the presentation level.
Try inserting and updating the date like this:
CAST(FLOOR(CAST(#DateTime AS float)) AS datetime)
We have this in a UDF and it basically strips the time part from a datetime.
In VB you can use the Date() function to return the current date with no time element.
If you an use an ADO Parameter object with a Command object then the OLE DB provider should handle the conversion of a VB Date type to the SQL Server DATETIME value.
In SQL Server (pre SQL 2008 DATE type) you should create a CHECK constraint on the column to ensure it is not possible to add a date with a time element (note I've used an unambiguous language 'safe' format for my DATETIME literals) e.g.
ALTER TABLE MyTable ADD
vb_date DATETIME NOT NULL
CONSTRAINT vb_date__no_time_element
CHECK ((vb_date = DATEADD(DAY, DATEDIFF(DAY, '1990-01-01T00:00:00.000', vb_date), '1990-01-01T00:00:00.000')));
I would just use DateSerial to create the date you need. You pass it a year, month and day and it gives you a date with midnight as the time. You can then use it to pass as a parameter to an ADO command or similar. When you read it, it will have midnight so that isn't a problem. I like it better than DateValue as there is no string conversion. If you really want you can create your own function like DateValue that uses DateSerial.
Function JustTheDatePlease(ByVal dtSource As Date) As Date
JustTheDatePlease = DateSerial(Year(dtSource), Month(dtSource), Day(dtSource))
End Function
If for some reason you aren't using parameterized queries, and you really should have a good excuse for this, you can use the ODBC canonical form of a date in your queries. You just format the date as {d 'yyyy-mm-dd'} for example {d '2009-04-06'}.