Issue with Date format in SQL - sql

I am currently using SQL Server 2008. I am extracting a column F254 value from a SQL query where it is returning the date format in MM/DD/YYYY (e.g. 8/17/2017).
I need the output to be in format YYYYMMDD (e.g. 20170817).
Note that the column F254 is of datatype char(10) and I cannot change the datatype.
I have tried below but the getting the needed output
H.F254 AS Original_Date, --> 8/17/2017
CONVERT(VARCHAR(10), H.F254, 111) AS eg1, --> 8/17/2017
REPLACE(CONVERT(VARCHAR(10), H.F254, 103), '/', '') AS eg2 -->8172017
CONVERT(VARCHAR(9), H.F254, 112) AS eg3 --> 8/17/2017
I have also checked the following Date Format but its not working

I think you have to convert it to a date first!
select convert(varchar(10),cast(H.F254 as date),112)

Related

SQL Server : change date format

I need to change the date format from 'yyyy-mm-dd' to 'dd.mm.yyyy'.
I have data in my table like this '2018-08-08', I need convert it to '08.08.2018'.
I have tried:
UPDATE daily_tasks
SET date = REPLACE(date, date, CONVERT(VARCHAR(255), daily_tasks.date, 102))
WHERE 1;
But, it doesn't work.
Ideally you should be storing your dates as bona-fide date columns, not as text. That being said, the date text '2018-08-08' is in fact in an ISO format, and would still allow you to do things like sort and compare against other date literals, so it is not so bad.
But converting this text to a '08.08.2018' format is the wrong thing to do. If a anything, you might want to consider adding a new date column new_date to store this date information. Do that, and then populate it with:
UPDATE daily_tasks
SET new_date = TRY_CONVERT(datetime, date);
Store your date as DATE datatype and when you read data from database use
DECLARE #myDate DATE = '2018-08-08'
SELECT FORMAT(#myDate, 'dd.MM.yyyy')
SELECT CONVERT(VARCHAR(10), #myDate, 104)
Your syntax looks like SQL Sever, so i would do :
UPDATE daily_tasks
SET Col = REPLACE(CONVERT(VARCHAR(10), daily_tasks.date, 103), '/', '.')
WHERE . . . ;
However, i would not recommend to do this, just use CONVERT() with SELECT statement whenever necessary :
SELECT REPLACE(CONVERT(VARCHAR(10), daily_tasks.date, 103), '/', '.')
Regardless of the database, dates are stored in an internal format. This is the correct way to store dates. Do not store dates as strings.
You can specify the format when you query:
CONVERT(VARCHAR(255), daily_tasks.date, 102)
Or, you can even add a computed column to provide this information:
alter table daily_tasks
add date_display as ( CONVERT(VARCHAR(255), daily_tasks.date, 102) ) ;
You could convert the date column to a varchar to store the date in your specified format. However I strongly recommend against this. You should leave it stored as a date.
If you want to do a SELECT to get the data out then you can convert it to your specified format like this:
SELECT CONVERT(VARCHAR, daily_tasks.date, 4)

Convert to DATE T-SQL

I have a field with date in the format dd.mm.yyyy E.x. 29.05.2016. I want to SELECT it as DATE but I get an error when I try the following:
CAST([PublishedDate] AS DATE) AS PublishedOn
Conversion failed when converting date and/or time from character string.
Reading this I tried the following:
CONVERT(VARCHAR(10), [PublishedDate], 126) AS PublishedDate
But it doesn't change the format.
How do I SELECT to have it in YYYY-MM-DD format.
EDIT: I have 3 different date fields with all three having different formats: dd.mm.yyyy | yyyy-mm-dd | yyyy/mm/dd. I want to select all of them with the same format. Since I use this query to build reports, right now I have dates in different formats. Doing the following:
CONVERT(VARCHAR(10), [PublishedDate], 104) AS PublishedOn
CONVERT(VARCHAR(10), [ValidFromDate], 104) AS ValidFrom
Gives me the following
You should use the right format, in your case it would be:
CONVERT(date, [PublishedDate], 104) AS PublishedDate
Also, once it's in a date, datetime or other date datatype, it doesn't have a format at all.
edit: Once you have your values in a date datatype, of course you can recast to a varchar to get the visual representation of the date you need.
edit2: If you want a date datatype, you should convert to date: CONVERT(DATE, [your column], [your format]).
If you want a nvarchar datatype, you should convert to nvarchar: CONVERT(nvarchar(x), [your column], [your format]).
You have an nvarchar that you want to display in a certain format, so you should first convert to date, then back to varchar (I doubt you need unicode):
CONVERT(VARCHAR(10), CONVERT(date, [PublishedDate], 104), 126)
The 104 you have to change for columns that are currently in a different format.
The best solution by far, is to change the datatypes to date. That is a bit of work, but definitely worthwhile.
If you really want the string do like this:
CONVERT(char(10), CONVERT(date,[date], 104),126) AS PublishedDate
Convert the string to date, using the 104 format (dd.mm.yyyy), as it is your original format, then convert the date into string, using the 126 format (yyy-mm-dd)
If you have a newer version of SQL Server, you may try
SELECT COALESCE(TRY_CAST(adate AS DATE), TRY_convert(DATE, adate, 126), TRY_convert(DATE, adate, 104)), format
FROM (
VALUES ('26.04.2017', 'dkformat') ,
('01.01.2017', 'EU format'),
('12.12.12', 'unknown format')
) a(aDate, format)
But you are going down a dangerous path, when you are trying to guess what format your source is in. Been there, done that, had the t-shirt.
I still hate the 0.1% conversions that are wrong.
This solution will result in NULLs, so you can see where your conversion did not succeed.

SQL - Unable to Convert a string in to YYYYMMDD format

I have a table that one of its columns is XML data type.
This XML value includes a TimePeriod value that looks like this:
"{start:{align:'Start',date:'2011-05-20T00:00:00'}"
I managed to extract only the date from this string with the following query:
SELECT SUBSTRING(configuration.value('(/ActiveService/#TimePeriod)[1]','nvarchar(50)'),
CHARINDEX('''', configuration.value('(/ActiveService/#TimePeriod)[1]','nvarchar(50)'),28)+1,10 )
FROM [MySystem].[dbo].[MyServices]
so i got this as the result: 2013-11-01
But, now i need to convert it to this format: YYYYMMDD
And when I'm using CONVERT to format 112 I Still get the same result: 2013-11-01
Why?
It you took value from xml as varchar, you cannot convert it into format YYYYMMDD (because it's already varchar), you have to convert it to date (or datetime first):
select convert(varchar(8), convert(datetime,
substring(
#data.value('(/ActiveService/#TimePeriod)[1]','nvarchar(50)'), 29, 10
), 120), 112)
But in your case it could be easier just remove -, by replace(<your value>, '-', '').
sql fiddle demo

Wrong type in datetime column SQL Server

I have an application in asp. I insert data into SQL Server into a column of datetime type.
Let me give you an example for my question:
when I have the date 10/02/2012 and I insert it into SQL Server I see the data like this:
2012-10-02
but I would like to have it like this: 2012-02-10
When I have the date 29/02/2012 and I insert it into SQL Server I see the data in the correct format : 2012-02-29.
How can I manage the correct type I want?
The collation of database and table is Greek_CI_AS , in my language
any ideas how to fix it?
There are a few possibilities, but they all relate to the date format settings of the system components your strings are passing through (i.e. both the ASP runtime and your SQL Server).
There is a date format setting in SQL Server http://msdn.microsoft.com/en-us/library/ms189491.aspx
In ASP, the parsing of strings in VBScript depends upon the settings in effect during the parse - basically, http://support.microsoft.com/kb/306044
You can use CONVERT() to control the date format and you can specify a smaller target string to crop the result:
SELECT CONVERT(NVARCHAR(10), GETDATE(), 21) -- YYYY-MM-DD
SELECT CONVERT(NVARCHAR(10), GETDATE(), 102) -- YYYY.MM.DD
SELECT CONVERT(NVARCHAR(10), GETDATE(), 105) -- DD-MM-YYYY
SELECT CONVERT(NVARCHAR(10), GETDATE(), 110) -- MM-DD-YYYY
SELECT CONVERT(NVARCHAR(5), GETDATE(), 105) -- DD-MM
SELECT CONVERT(NVARCHAR(5), GETDATE(), 110) -- MM-DD
SELECT CONVERT(NVARCHAR(4), GETDATE(), 102) -- YYYY
-- To get YYYY-DD-MM, put two of the above together:
SELECT CONVERT(NVARCHAR(4), GETDATE(), 102)
+ '-' + CONVERT(NVARCHAR(5), GETDATE(), 105)
To force a date format for insertion, you can do a similar thing:
-- Insert in Italian dd-mm-yy (e.g. 10th February 2012)
INSERT INTO user_table VALUES (CONVERT(DATETIME, '10-02-12', 5));
-- Insert in USA mm-dd-yy (2nd October 2012)
INSERT INTO user_table VALUES (CONVERT(DATETIME, '10-02-12', 10));
See Microsoft MSDN reference CAST and CONVERT (Transact-SQL).
---- ANSWER TO ADDITIONAL QUESTION ----
I find your latest comment a little ambiguous. If you're asking how to search on a datetime field between two dates that you have in string format, then, try something like this:
SELECT *
FROM user_table
WHERE mydate BETWEEN convert(Datetime,'20/02/2012',103)
AND convert(Datetime,'01/03/2012')
whereas, if you are trying to search on an nvarchar field with two dates in string format, then, try something like this:
SELECT *
FROM user_table
WHERE convert(Datetime, mynvarchar, 103)
BETWEEN convert(Datetime,'20/02/2012',103)
AND convert(Datetime,'01/03/2012')
However, this is terribly inefficient. If you are going to be doing date searches a lot, I highly recommend storing your date field in datetime format. If you have a business requirement to store the nvarchar version, that's okay, but you can use dynamic columns, such as:
CREATE TABLE user_table
(
mynvarchar NVARCHAR(10), -- Date as a String in DD/MM/YYYY format
mydatetime AS CONVERT(DATETIME, mynvarchar, 103) PERSISTED
);
The advantage of this is the mydatetime field automatically updates itself and can be used in indexes and constraints if you wanted it to, but, you can manage it by manipulating the mynvarchar business columns.
In future, can I please request that when you ask question, that you provide more concrete examples, i.e. the name of your table, the name of your columns, so I don't have to keep inventing these.

Convert/format a column in a SQL Server 2005 select statement

I have an SQL query which is select DateOfBirth from people, and it shows up in the result pane as
DateOfBirth
07/07/2010 5:08:02
07/09/2010 5:08:02
07/13/2010 5:08:02
I want to format as,
07/Jul/2010
09/Jul/2010
13/Jul/2010
NOTE: DateOfBirth column has datatype nvarchar(50), not datetime...
This is a little tricky as the best way to do this is to take the varchar convert it into a datetime and then format it. Annother complication is that the format you want is not a format that SQLServer will output.
So.
SELECT CONVERT(DateTime, DateOfBirth) from people
will get you the date time and we can then convert it to a string format as follows
SELECT CONVERT(DateTime, DateOfBirth), 106) from people
this will produce the string output 'dd Mon YYYY'
then its just a matter of replacing the spaces with '/'
SELECT REPLACE(CONVERT(varchar, CONVERT(DateTime, DateOfBirth), 106), ' ','/') FROM people
will get you the format you want.