SQL Server: convert StartDATE 20140804 Nvarchar to Datetime2 - sql-server

I'm using SQL Server 2008 and I did an import from a flat file. I couldn't import the datetime column properly so I specified it temporarily as a nvarchar(50).
Now I want to convert it to datetime2 format. However when doing so, I get the error
Conversion failed when converting date and/or time from character string.
The data that is currently in my nvarchar(50) column looks like this:
20140804
And I need to convert it to:
2014-08-04 00:00:00.0000000.
Note that I do not only want to convert one date, but all StartDATE values in my table and insert them to another table
Any help is appreciated.

Insert into targettab(datecol,<othercols....>)
select cast(datefield as datetime2),<othercols...> from sourcetab
You can use cast function

you need to convert to char first because converting to int adds those days to 1900-01-01
select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))
here are some examples
select CONVERT (datetime,5)
1900-01-06 00:00:00.000
select CONVERT (datetime,20100101)
blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit
convert to char first
declare #i int
select #i = 20100101
select CONVERT (datetime,convert(char(8),#i))

SELECT convert(varchar, StartDATE , 113) from ur table

Related

Convert Varchar date format from yyyy-MM-dd to yyyyMMdd in SQL

Hi I am trying to convert Varchar date format from yyyy-MM-dd to yyyyMMdd in SQL.I tried the below approaches but nothing is working.
Declare #doj VARCHAR(10)
Set #doj='2022-01-01'
Select convert (VARCHAR,#doj,112)
select format(#doj,'yyyyMMdd')
SQL engine is not converting to the required format.If I declared doj variable to date then it is working as expected.How to make it work if the doj is varchar?
You can just convert to datetime and back again using explicit style numbers:
Declare #doj VARCHAR(10) = '2022-01-01';
SELECT CONVERT(varchar(10), CONVERT(datetime, #doj, 126), 112);
db<>fiddle
Quite why you are storing dates in varchar in the first place is another question...

Converting a varchar date to date datatype in mssql

My column is storing value as 201909(i.e September 2019), I need to convert it to format 2019-09-01 and store in it another column in a MSSQL .Please help
You can add a statinc '01' string with your current string and then try to convert as below-
DECLARE #D VARCHAR(20)
SET #D = '201909'
SELECT CAST(#D+'01' AS DATE)
Output is-
2019-09-01

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

Which settings provide SQL Server default datetime format?

Say, I have a table like this :
Table name "DateTimeFormatCheck" >
I used below query to insert :
Insert into [dbo].[DateTimeFormatCheck] ([DateTimeCheck]) values('11/19/2014 1:29 PM')
It inserted date like 2014-11-19 13:29:00.000 , but my insertion format(M/d/yyyy h:m tt) is not same as inserted date.
Now i want to know How SQL Server detect my string date format that i have provided ? and Why it always provide this format yyyy-MM-dd HH:mm:ss after insertion?
Thanks
Don't do that! Don't use strings instead of dates and don't use a culture-specific date or datetime format, it's a recipe for disaster.
SQL Server doesn't have a "date format", just formats it uses to convert dates to and from strings. One of them is the default, controlled by the server's collation. You can neither assume nor should you depend on a specific collation, so you should avoid conversions whenever possible. Moreover, passing a string value can prevent SQL Server from using indexes on date columns because it would have to convert the string to the underlying column type.
It's far easier and safer to pass dates as date-typed variables or parameters. You avoid the entire conversion mess this way, to and from and avoid SQL injection attacks.
There's no reason to pass strings instead of dates to the server. All SQL Server clients (including ADO.NET) allow you to execute parameterized queries. ORMs like NHibernate and Entity Framework also generate parameterized queries for date-typed columns.
Whenever you need to create a string literal, use one of the invariant formats like 20140913 or 2012-11-07T18:26:20
You can read more about it at Writing International T-SQL Statements
The format of sqlserver is yyyy-mm-dd, but you can define your input by execute the command
set dateformat dmy -- to accept dmy format
set dateformat mdy
select cast( '11-9-2014' as date)
set dateformat dmy
select cast( '11-9-2014' as date)
updated
Ideally you can not try to change format, you can validate your data and then insert.
Whenever we insert into datetime datatype, sqlserver will implicitly try to convert into mmddyyy hhmmss format. so if you given date as 19/11/2014 , it convert into 11/19/2014 means 19th nov 2014.
But if you give more than 12 in the middle portion, it will not convert implicitly and throw the error of conversion.
Other than mmddyyyy format, you must use to cast or convert function explicitly to allow the data insert or update.
Before the casting you can use ISDATE or TRY_PRASE or PARSE function in sqlserver, will check to conversion possible or not.
you can create a function or just add line as
declare #dt varchar(50) = '19-11-2014 10:10:41'
declare #dTable table ( datecolumn datetime)
INSERT into #dTable values (
case
when isdate(CONVERT( varchar(50), #dt)) = 1 then CONVERT( varchar(50), #dt) --'19-11-2014 10:10:41'
when isdate(CONVERT( varchar(50), #dt, 103) ) = 1 then CONVERT( datetime, #dt , 103 ) --'19-11-2014 10:10:41'
when isdate(CONVERT( varchar(50), #dt, 102) ) = 1 then CONVERT( datetime, #dt , 102 ) --'19-11-2014 10:10:41'
--when --give other format as above given and if not set in any dateformat , then simply return null
else
null
end )
select * from #dTable

Convert varchar column to smalldatetime

I have a table with 800+ records. In this table I have a column named 'Data' of varchar(10) datatype which contains dates in dd.MM.yyyy format.I want to convert it to smalldatetime.
I've tried converting it using Enterprise Management Studio Express, but I receive this error:
The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value.
How can I convert it?
I think you'll need to do a little string manipulation to get this to work as I think SQL is expecting 'MM.dd.yyyy'. So, update your table to flip-flop the month and day first, then the conversion should go through.
update YourTable
set Data = SUBSTRING(Data,4,3) + LEFT(Data,3) + RIGHT(Data,4)
You can use:
SELECT ID, CAST(VarcharCol As SmallDateTime) as DateTimeCol From Test1
This will return a table with varcharcol values as smalldatetime
Then update the content of varcharcol with the new values.
If you don't want implicit conversion to smalldatetime, you should use CONVERT and the argument style.
dd.MM.yyyy format correspond to style 104.
For example :
SELECT CONVERT(smalldatetime, '31.12.2018', 104) AS "Result"
Result
------
2018-12-31 00:00:00

Resources