Casting nvarchar to date with a formatting in SQL-Server - sql

I'm using SQL Server Management Studio. There is one table in my database containing dates which are stored as nvarchar(255). I want to migrate the data of this table to a new table which I call Converted_Dates and store this data as date. Also, I want them all to be formatted like this YYYY-MM-DD
Currently the Dates table looks like this:
**Dates**
15/6/2011
16/6/2011
2013-03-30
2013-04-16
...
I want the new table to look like this:
**Converted_Dates**
2011-06-15
2011-06-16
2013-03-30
2013-04-16
...
I execute this query but formatting of dates remains the same, only the data type changes from nvarchar(255) to date.
USE [reporting_database]
GO
INSERT INTO [dbo].[Converted_Dates]
SELECT
cast(Dates as date)
FROM [dbo].[Dates]
GO
Any advice on how to cast the data from the old table to a new one in a preferred format?

The value of date and datetime data type is not stored with format in sql server. If you want to see the date in a different format you can manipulate the way that date and datetime data types are displayed when converted to a varchar (or nvarchar,nchar,char) data type using some built in functions.
You should store your dates as date data type, and if you can format them at the application level, do so there. If you must format them in sql, then use convert() styles.
select convert(char(10),getdate(),120)
returns: 2017-05-01
In sql server 2012+ you can use format()
select format(getdate(),'yyyy-MM-dd')
returns: 2017-05-01
But format() is much slower, take a look here: format() is nice and all, but… - Aaron Bertrand

Related

Simple way to standardize varchar "dates" to single date format in SQL?

I have a table in a postgres database with a varchar date column that mixes MM/DD/YY with MM/DD/YYYY data formats. For example:
1/17/89
1/28/2018
12/30/2006
10/1/17
I'd like all of the dates to follow a MM/DD/YYYY format:
1/17/1989
1/28/2018
12/30/2006
10/1/2017
I'm aware it's not a best practice for dates to be in a varchar field, but I did not create this table and I cannot change the data type. Is it possible to use SQL to make this kind of change to my table?
I'm aware of similar questions like this one, but this seems a bit more than what I'm looking for, and I can't seem to extract an answer from it that's appropriate for my issue.
This question seems closer to what I'm looking for, but again, I can't seem to implement the answer. How would it know which table and field to make changes to? (I'm a total SQL noob if you can't tell).
You can try to use this code:
SELECT to_char(to_date(my_date,'MM/DD/YY')::TIMESTAMP, 'MM/DD/YYYY') as new_varchar_date FROM my_table;
-- for update the actual values
UPDATE my_table SET my_date = to_char(to_date(my_date,'MM/DD/YY')::TIMESTAMP, 'MM/DD/YYYY');
At first you need to convert the varchar to date, then to timestamp and then to varchar again.
Result should look like:
01/17/1989
01/28/2018
12/30/2006
10/01/2017

T-SQL Dates using Convert() function?

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.

Changing SQL VARCHAR2 date to another date format

I have a date (stored as a VARCHAR2) in a database with the format:
20090123_163842.865
yyyyMMdd_hhmmss.ttt
and I want to make a SQL sentence to obtain:
23/01/2009 16:38:42,865
dd/MM/yyyy hh:mm:ss,ttt
MY objective is to add it manually (I know that data can be exported from database, and imported into Excel, but I want to do it manually) to Excel as a recognizable Date.
How should my SQL sentence be?
I have tried to to it by:
select TO_TIMESTAMP(my_time_utc, 'YYYYMMDD_HH24MISS.FF3') from myTable
but I am only able to obtain:
2009-01-23 16:38:42.865
Thanks
It never ceases to amaze me how many people confuse these operations.
First you need to convert the varchar 'fake date' to a real date: use to_date for this.
Then you need to convert the date to a varchar for presentation: use to_char for this.
select to_char(to_date(column, 'yyyyMMdd_hhmmss.ttt'), 'dd/MM/yyyy hh:mm:ss,ttt')
from your_table;
should do what you want.
When oracle retrieve a date field from database and show it to you a cast implicit conversion is made. The format pattern for this conversion is set in oracle configuration. Quoting oracle doc:
The default date format for an Oracle date value is derived from the
NLS_DATE_FORMAT and NLS_DATE_LANGUAGE initialization parameters
If you perform query from Excel, your actual query is enougth because excel know date format and is able to read from Oracle with out problems.
If you do a copy-paste from your screen results to excel, then you should cast back date to varchar with your desired format or, of course, change oracle configuration to match your locales.

Update table Error Using Convert Function In SQL Server 2005

I have a table with two columns, all of them are datetime value
Such as, Column A with value ‘07/09/2012 14:13:34’
Now, I want to update column A to yyyymmdd by statement
Update Change_Date
SET A = CONVERT(VARCHAR(8),A,112)
It shows succsessful message but with no effect (no update value to 20120907) in my table Change_Date.
Any help will be greated, thank you!
A datetime fields saves a date time. How you see that date time is a result of the tool you're using to inspect the data, whether it is Management Studio, or your own software that's printing something from the database.
I strongly recommend keeping it as a datetime field. This will allow you to do date-related operations, such as subtractions and comparisons. If you want to change how your users see the date, then format your date at the presentation layer.
What's happening in the code you've posted is that you're setting the value of A to the same date that it already is. The fact that you're setting that value by means of a string in another format has no relation, SQL server will always have to parse your string input into a date that it can understand. This is why you're not getting an error message. The operation is working, only it's not changing anything.
You can select the date column in specified format or make a view which selects the column value in yyyymmdd format:
SELECT CONVERT(VARCHAR(8), A, 112) FROM Change_Date
It's because the datatype of the column is DATE or DATETIME and it has specific format. If you want to update the column with specific format, make another column and make its datatype VARCHAR. I believe 112 is yyyymmdd format.
I strongly suggest that you keep it AS IS. Database is the storage of data and not for viewing purposes. It is easy to perform task for dates if your data type is DATETIME or DATE. If for instance you want to retrieve the dates with specific format, that's the time you convert your date.
Hope this makes sense.

Change default dateformat stored in a database

I am seeeing my dates are stored in database in this format for a column (datetime datatype) 2011-01-14 10:15:41.787 i.e YYYY-MM-DD way . How could I make the default storage in YYYY-DD-MM format . Do I need to set that for all the DBS, or I can set it for single DB and how ?
I have the column in datetime datatype, right now it is saving as
2011-01-14 10:15:41.787 , my question is how can I set the db to store it as
2011-14-01 10:15:41.787
That is the crux of the confusion. Just because SQL Server Management Studio displays a datetime column in that format does not mean that it is stored AS TEXT YYYY-MM-DD hh:mm:ss.zzz. It is stored as binary, something like 0000101000001010..
Your dates are stored in SQL Server as a series of bytes (bits really) that make up some numeric value that is an offset from 1900-01-01. There is no inherent format the the dates. What you are referring to is that SSMS by default shows [display] datetime columns as YYYY-MM-DD hh:mm:ss.zzz. If you use a front-end programming tool, that too may impose a default [display] format unless you have asked for another one.
There is absolutely NO way to make SSMS show datetime data in another format through options or configuration. If you must, you would have to update the SQL query to convert the datetime column to a VARCHAR column containing the TEXTual equivalent in a particular format. That may be useful in SSMS, but would be bad when used as a data source to front-end GUI/web apps - since the values are not datetime and cannot be used for interval calculation, graphing, bound to date controls etc.
See this example of displaying time (getdate()) as YYYY-DD-MM, a very unusual format. Notice the date field/variable has to be used twice:
select stuff(convert(char(7), getdate(), 120), 5, 0, '-' + convert(char(2), getdate(), 3))
DATETIMEs are stored internally as two 4 byte integers, so firstly you are seeing a formatted representation for the UI - it's not actually stored in a particular date/time format as such.
e.g. if you insert just a date like "2010-01-01" then it will still hold the time element: 2010-01-01 00:00:00.000
If you're only interested in the DATE part, then you can format the DATETIME for output either in your front-end code or via your query:
e.g.
SELECT CONVERT(VARCHAR(8), GETDATE(), 121)
So even if the DATEs you insert contain a time, that will be ignored when returned. You could also ensure you only insert dates without the time specified - you need to handle that in whatever code is doing the INSERTs. e.g. from .NET, instead of passing in DateTime.Now you could pass in DateTime.Now.Date.
In SQL Server 2008, there is a DATE datatype which is there to only store a DATE (without time) which is really what you want in this kind of scenario.