SQL Server - Set Date Format at insertion - sql-server

Does anyone know the correct syntax for this format: dd-mmm-yyyy. E.g. 04-DEC-2016
Basic Insert
INSERT INTO GoodTbl (GoodID, GoodDate)VALUES (7,'12-04-2016')
I did this and it worked
INSERT INTO GoodTbl (GoodID, GoodDate)VALUES (7,(CONVERT(DATETIME,'12-04-2016', 105)));
but 106 is the correct code. However using 106 (as shown) does not work.
INSERT INTO GoodTbl (GoodID, GoodDate)VALUES (7,(CONVERT(DATETIME,'12-04-2016', 106)));
Is there a different way to write this?

If 2012+ you can use the format()
Select Format(GetDate(),'dd-MMM-yyyy')
Returns
03-Dec-2016
Another option is
Select Replace(convert(varchar(25),GetDate(),106),' ','-')
You realize that these conversions are string, so I am assuming the destination field is a string/varchar
Use VARCHAR instead of DateTime, then the following:
INSERT INTO GoodTbl (GoodID, GoodDate)
VALUES (7,Replace(convert(varchar(25),cast('2016-12-04' as date),106),' ','-'))

Related

Check data type format of every value of a column in SQL Server

I have a table_1 that has column dob which has datatype nvarchar(max). Now I want to check every date whether it is in datetime format or not.
The dates which are in datetime format should be copied to table_2 that has column with a datatype of datetime.
Any help how can I do this?
If you are using SQL Server 2012 or later, then TRY_CONVERT can help here:
SELECT *
FROM yourTable
WHERE TRY_CONVERT(datetime, dob) IS NULL;
This would return every record from your table where the dob text field is in some format which SQL Server cannot natively convert to a datetime.
This will insert all the strings can be converted into Table_2
INSERT INTO Table_2 (DateTimeColumn)
SELECT dob
FROM Table_1
WHERE TRY_CAST(dob AS DATETIME) IS NOT NULL;
It is a very bad habit to store datetime values in a string. The reason why: Date-Time formats differ around the world and depend on your system's culture settings. Even worse, some format depend on a given language. Try this out:
SET LANGUAGE ENGLISH; --try with GERMAN to see the effect on "Decemeber"
SET DATEFORMAT ymd; --try with "ydm" or "dmy"
DECLARE #tbl TABLE(dob NVARCHAR(MAX));
INSERT INTO #tbl VALUES('blah') --just a wrong value
,('20201231') --ISO, "unseparated YMD-format (see CONVERT with 112)
,('2020-12-31') --ISO8601
,('2020-31-12') --European with leading year
,('12-31-2020') --USA (see CONVERT with 110)
,('31-12-2020') --European (see CONVERT with 113)
,('31 December 2020') --language dependant (see CONVERT with 113), try with German "Dezember"
,('2020-02-30'); --Invalid, there's no 30th of February
SELECT t.dob --Your value
,[cast] = TRY_CAST(t.dob AS DATETIME) --CAST relies on the system's settings (might work on your machine but can break on a customer's machine
,[convert] = TRY_CONVERT(DATETIME, t.dob, 112) --CONVERT allows to use the style paramter, better than CAST, but more strict
,[parse] = TRY_PARSE(t.dob AS DATETIME USING 'en-US') --Parsing allows to mention the culture. You do not need to specify the language as a general setting
,[xmlCast] = CAST(t.dob AS XML).value('. cast as xs:date?','datetime') --Works below v2012, but can deal with ISO8601 only.
FROM #tbl t;
Play with the settings
You can use GERMAN instead of ENGLISH. The entry with December will not work any more. You can change the general date format to any combination of ymd and find, that some formats stop to work while others start to work.
TRY_CAST, TRY_CONVERT and TRY_PARSE will need a version of v2012 or higher.
If you are running an older system you should upgrade ( :-) ). The only chance with an older system is a XML hack, but this is very tightly bound to ISO8601.
Finally: For your next question, please try to add more information. State some of your input values, mention your RDBMS with version and try to set up a mockup with DDL and INSERT (look what I've done above).
Hint: Very dangerous...
Try to insert a value like 2020-05-06 and you will find, that some styles read this as the 5th of June, while others return the 6th of May. Returning wrong values is worse than returning NULL or throwing an error...
StayAtHome
StayHealthy

Troubleshoot conversion failed when converting date and /or time from character string

I know this has been addressed 1000 times but something screwy is going on and I need help with ideas to troubleshoot.
Using MS SQL Server 2012
I have a date stored as INT in the YYYYMMDD format.
I need to turn that into a date and I always use this:
CONVERT(DATE,CONVERT(VARCHAR,YYYYMMDD),101)
*I know not specifying the length of the varchar is bad form but where I'm doing this has never caused an issue and just to be thorough I tried it anyway to no avail.
That conversion always works. Always, until today.
Today, this conversion doesn't work and I get the above mentioned error in title.
One thing I've done is run part of the query to look at the values to make sure I don't find something dumb like this in my values:
20170102
20170304
-->2017ABCD
20170704
What else can I do?
To expand on my initial comment
Example
Declare #YourTable table (SomeCol varchar(25))
Insert Into #YourTable values
('20170102'),
('20170304'),
('2017ABCD'),
('20170704')
Select SomeCol
,AsDate = try_convert(date,SomeCol)
From #YourTable
Returns
SomeCol AsDate
20170102 2017-01-02
20170304 2017-03-04
2017ABCD NULL
20170704 2017-07-04

SSIS Convert m/dd/yyyy to yyyymmdd with inconsistencies

I'm loading many files into a SQL SERVER database. I have one flat file that has a Date Column coming in as string[DT_STR].
I have TWO "date fields" in my database. One is varchar, one is datetime.
Converting the datetime column is no issue, I just use Data Conversion/Derived Column if necessary. However, this varchar column is giving me trouble. Our database values for this column should be in yyyymmdd format. However, on this single file the format of the dates change.
Normally I'd do a SUBSTRING(...) expression here, but the difficulty is that the format of these dates change. some examples of values could be
08/16/2017
8/16/2017
08/6/2017
08/06/2017
10/6/2017
10/06/2017
This makes the challenge harder. I tried LEN([DATE]) == NUM_HERE ? do_THING : OTHER_CALC, but this approach failed because the length of 10/6/2017 is the same as 8/06/2017 which will give me the wrong result. Does anyone have a good workaround for this?
Perhaps a simple convert to date and then into the final format. If 2012+, use try_convert() to trap any bogus dates.
Example
Declare #YourTable Table ([SomeCol] varchar(50))
Insert Into #YourTable Values
('08/16/2017')
,('8/16/2017')
,('08/6/2017')
,('08/06/2017')
,('10/6/2017')
,('10/06/2017')
Select *
,Formatted = convert(varchar(8),convert(Date,SomeCol),112)
from #YourTable
Returns
SomeCol Formatted
08/16/2017 20170816
8/16/2017 20170816
08/6/2017 20170806
08/06/2017 20170806
10/6/2017 20171006
10/06/2017 20171006
Convert the varchar data to datetime and convert that to a formatted string
SELECT CONVERT(varchar,(CONVERT(datetime, '8/6/2017')),112)

SQL Server Converting varchar to datetime

I got a problem in SQL Server with converting a varchar to datetime. I would like to convert/update whole column [datelog] in table:
[dd.mm.yyyy hh:mm:ss]` to `[yyyy-mm-dd hh:mm:ss]
In SQL Server 2012+ you can use PARSE or TRY_PARSE to parse a text value according to a specific culture.
Assuming your text follows the German culture ('de-DE') you can parse it to datetime with :
select PARSE('24.11.2015 13:10:55' as datetime using 'de-DE')
eg:
select PARSE(datelog as datetime using 'de-DE')
The real solution though would be to use the correct field type, ie datetime. It's almost guaranteed that someone, somewhere will either enter text with the wrong format or try to convert the text using the wrong culture.
Date types on the other hand, have no format, they are simply binary values. Using them is faster, safer and easier.
Tricky solution,
DECLARE #inputDate AS VARCHAR(20)='21.11.2015 06:59:00' -- [dd.mm.yyyy hh:mm:ss]
SET #inputDate = REPLACE(#inputDate ,'.' ,'/')
SELECT CONVERT(VARCHAR(24) ,CONVERT(DATETIME ,#inputDate ,103) ,121) OutputDate -- [yyyy-mm-dd hh:mm:ss]
Still you need to change as per your table columns.
temp table with one column of type varchar
create table #temp3 (someDate varchar (30))
insert into #temp3 values ('23.03.1989 15:23:43')
using a combination of concat, substring and right
select concat
(
SUBSTRING(someDate,7,4),'-', SUBSTRING(someDate,4,2),'-',SUBSTRING(someDate,1,2), ' ', right(someDate, 8)
)
from #temp3
gives: 1989-03-23 15:23:43

How to set date format for the result of a SELECT statement in SQL Server

I know how to use CONVERT function in SELECT statement to change the format of the Date column:
SELECT
StationID
, CONVERT(varchar, [Date], 101) as Date
, Value
FROM my_table
But I was wondering if I can set the date format in general before running the SELECT statement, when I don't know the name of the date column in the following SELECT statement:
SELECT * from FROM my_table
Is any SET statement or other T-SQL that I can run before my SELECT statement so that I can change the Date format temporarily?
Thank you
No.
In particular, any date columns which you select are not actually formatted at all, but are instead returned down the wire as an actual piece of date data in a binary "format" which is used for dates. If you are seeing them formatted, it's because your client (either management studio or some other tool) is converting them to strings to display.
When you use SELECT *, there is obviously no way to tell SQL Server to do any conversions on any particular columns, so the data is going to be returned in whatever the data types of the underlying query returns. So regardless of whether your data types are really date or not, no manipulation is going to happen at that point anyway.
I'm pretty sure there's no way to do what you're asking. However, there are ways to format the date string when you output it using your programming language.

Resources