Converting varchar datatype to datetime datatype using SQL 2012 management studio - sql-server-2012

I have a column which has ddmmmyyyy:hh:mm:ss.nnnnnn it is stored as varchar(25). I need to save it as datetime in the same column. I have tried using
update tablename
set columnname = (SUBSTRING(columnname,1,2) + '-' + SUBSTRING(columnname,3,3) + '-' +
SUBSTRING(columnname,6,4) + ' ' + SUBSTRING(columnname,11,8));
and then
alter table tablename
alter columnname datetime;
but later it shows up the error
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
How do I change it any other opinion or any modification for the above query. Please help. Thank you.

As per your given string format, you should use datetime2 data type
Your string format is almost correct, only 1 colon is extra after Year.
If you fix that thing, you can directly cast the varchar field into datetime2. For example first you can replace the extra colon with space by running following query,
UPDATE myTable
SET targetColumn = STUFF ( targetColumn , 10, 1, ' ')
-- ddmmmyyyy:hh:mm:ss.nnnnnn
-- \
-- this colon is extra which is at 10th position
After this you can directly ALTER your table and change the data type to datetime2.
Important: data in all the lines must contain valid date
Here is a test which shows how you can convert
CREATE TABLE testTable(testCol varchar(25));
INSERT INTO testTable(testCol)
VALUES('03Jan2014 18:33:39.999999');
ALTER TABLE testTable ALTER COLUMN testCol datetime2;
SELECT *
FROM testTable
DROP TABLE testTable;

It has already been answered here: Is there a way to convert a varchar to DATETIME in SQL SERVER 2008?
He uses: convert(datetime,'24/05/2012 09:56:06',103)
Although you might have to do some substrings to adapt to a format covered by convert: http://www.sql-server-helper.com/tips/date-formats.aspx

Add a new column
alter table t
add n datetime
Update the new column
update t
set n = datetimefromparts(
cast(substring(o,6,4) as int),
case substring(o,3,3)
when 'jan' then 1
...
when 'dec' then 12
end,
cast(substring(o,1,2) as int),
cast(substring(o,11,2) as int),
cast(substring(o,14,2) as int),
cast(substring(o,17,2) as int),
cast(substring(o,20,6) as int)
)
If you need to drop the old column
alter table t
drop column o

Related

Convert entire column from integer to datetime using SQL

I have a table with an entire column that contains integers. I know that these integers were previously datetime values. I want to update all values in this column to be datetimes. There are 1000+ plus rows. I've altered this column from an INT to varchar since all the errors I received didn't like me going from an INT to DATETIME but I am having the same issue with the varchar data type.
Example values in the column: 43873, 40706, 43873, ect
I have tried the following queries:
UPDATE WORKER SET INT_TIME = DATEFROMPARTS(INT_TIME,1,1);
UPDATE WORKER SET INT_TIME = CONVERT(datetime,INT_TIME,107);
I receive errors like
Conversion failed when converting date and/or time from character
string.
INT_TIME is the column I am trying to update all values to a datetime:
These look like Excel format. That suggests something like:
select dateadd(day, col, '1899-12-30')
ALTER TABLE [dbo].[WORKER]
ALTER COLUMN [INT_TIME] DATETIME
This statement alters the integer column to a datetime column and parses the values automatically.
You can use dateadd() function :
select dateadd(day, t.int_time, 0) as joining_date
from tabel t;
You can use update statement to update , before that you need to alter table definition also :
alter table worker
alter column int_time DATETIME
update worker
set int_time = dateadd(day, t.int_time, 0)
0 have a default date 1900-01-01 00:00:00.000

How to convert or cast int to string in SQL Server

Looking at a column that holds last 4 of someone's SSN and the column was originally created as an int datatype. Now SSN that begin with 0 get registered as 0 on the database.
How can I convert the column and it's information from an int into a string for future proof?
You should convert. CONVERT(VARCHAR(4), your_col)
If you specifically want zero-padded numbers, then the simplest solution is format():
select format(123, '0000')
If you want to fix the table, then do:
alter table t alter column ssn4 char(4); -- there are always four digits
Then update the value to get the leading zeros:
update t
ssn4 = format(convert(int, ssn4), '0000');
Or, if you just want downstream users to have the string, you can use a computed column:
alter table t
add ssn4_str as (format(ssn4, '0000'));
If you want to add leading zeros, use:
SELECT RIGHT('0000'+ISNULL(SSN,''),4)
First thing never store SSN or Zip Code as any numeric type.
Second you should fix the underlying table structure not rely on a conversion...but if you're in a jam this is an example of a case statement that will help you.
IF OBJECT_ID('tempdb..#t') IS NOT NULL
BEGIN
DROP TABLE #t
END
GO
CREATE TABLE #t(
LastFourSSN INT
)
INSERT INTO #t(LastFourSSN)
VALUES('0123'),('1234')
SELECT LastFourSSN --strips leading zero
FROM #t
SELECT -- adds leading zero to anything less than four charaters
CASE
WHEN LEN(LastFourSSN) < 4
THEN '0' + CAST(LastFourSSN AS VARCHAR(3))
ELSE CAST(LastFourSSN AS VARCHAR(4))
END LastFourSSN
FROM #t
If you are looking for converting values in the column for your purpose to use in application, you can use this following-
SELECT CAST(your_column AS VARCHAR(100))
--VARCHAR length based on your data
But if you are looking for change data type of your database column directly, you can try this-
ALTER TABLE TableName
ALTER COLUMN your_column VARCHAR(200) NULL
--NULL or NOT NULL based on the data already stored in database

SQL Server : convert nvarchar year to datetime

I am trying to convert nvarchar(5) year of birth (e.g. 1972) to a datetime (e.g. 1972-06-01) in a SQL Server table.
Something like:
UPDATE TableName
SET DateOfBirth = CONVERT(datetime, YearOfBirth + '/01/01', 103)
This throws an error
Conversion failed when converting date and/or time from character string
How can I solve this?
What you are doing needs two steps: store the value in the column as a date and then change the type.
In your case, a third step is needed, so the column is big enough to store the value string representation of the date value. I think this will work in SQL Server:
ALTER TABLE TableName ALTER COLUMN DateOfBirth NVARCHAR(32);
UPDATE TableName
SET DateOfBirth = YearOfBirth + '-01-01';
ALTER TABLE TableName ALTER COLUMN DateOfBirth Date;
The first ALTER TABLE alters the column to be wide enough for the new month and day. Then the date is constructed in a standard format (okay, leaving out the hyphens would be even more standard). Then the column is transformed to a date.
If you just want something that looks like a date -- and a lot of criticism on Stack Overflow ;) -- you can eliminate the third step.
This is all you need
UPDATE TableName
SET DateOfBirth = YearOfBirth + '-06-01'
Where YearOfBirth = '1972'

Converting Varchar into Date in data type

I am relatively new to SQL Server so I was wondering how to convert the data type from varchar to date format? I have a few thousands records so I need a query to help to convert the varchar to date in a single query.
I have the date in this format: yyyymmdd, in varchar(8) and I want to convert this into yyyymmdd, in date format.
Is there any queries to help me with this?
For various conversions between VARCHAR and DATETIME have a look at this link.
Actually in your case, since your VARCHAR is in yyyymmdd format, you could just:
convert(datetime, YourVarcharDateField, 112)
Simply Use this Inbuilt CONVERT Function, and Check this Link for formatting Dates
-- Use 101 if you have divider in your date
SELECT convert(datetime, '2014-01-02',101) as [DateTime]
-- Use 112 if you don't have divider in your date
SELECT convert(datetime, '20140131',112) as [DateTime]
Edited:
UPDATE yourTable SET field = convert(datetime, 'yourFieldName',112)
--This will update all of your field regardless of any particular row
--If you want to update any particular set of rows use `WHERE` clause
if you have more various formats goto to the given link.
Data types can be converted either implicitly or explicitly.
Implicit conversions are not visible to the user. SQL Server automatically converts the data from one data type to another. For example, when a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds.
Explicit conversions use the CAST or CONVERT functions.
The CAST and CONVERT functions convert a value (a local variable, a column, or another expression) from one data type to another
convert(datetime, '2013-05-04',101)
CAST ( expression AS data_type )
ALTER TABLE [dbo].[table] ADD ConvertedDate Date
UPDATE [dbo].[SysData] SET ConvertedDate = CAST(VarCharDate as Date)
ALTER TABLE [dbo].[table] DROP COLUMN VarCharDate
Use CAST OR CONVERT function to convert string to date
Try this:
SELECT CAST('20140102' AS DATE) AS convertedDate;
SELECT CAST(colName AS DATE) AS convertedDate FROM tableA; -- Replace column name and table name
OR
SELECT CONVERT(DATE, '20140102', 112) AS convertedDate;
SELECT CONVERT(DATE, colName, 112) AS convertedDate FROM tableA; -- Replace column name and table name
OUTPUT of both queries:
|convertedDate|
|-------------|
|2014-01-02 |
In SQL SERVER, there are two types of built in conversion techniques.
Convert
Cast
Convert having its own defaults so it will be outdated in upgraded version of SQL SERVER
better make use of CAST Conversion technique
In your scenario.Already having the date with datatype of Varchar(8) trying to Convert into Date
Solve in systematic manner.
Adding the one new Column in the existing table.
Alter Table Table_name Add changedDataTypeDate Date
Update the values in varchar datatype to Date Datatype
UpDate Table_name Set ChangedDataTypeDate = CAST(OriginalDataTypeDate as Date)
Again change the new column name into old column name.
Sp_Rename 'Tablename.changedDataTypeDate','OriginalDataTypeDate','COLUMN'
Its done.
Based on u r requirement.
Alter Table customer Add Purchase_Changedtype Date
Update Customer set Purchase_changedtype = CAST(Purchase_date as Date)
(If u need Time also replace Datetime istead of Date)
Alter table Customer Drop column Purchase_date
Sp_Rename 'Customer.Purchase_ChangedType','Purchase_Date','Column'

How to copy data from one table to another where column data types are different?

I have two tables.
NEW [contains data] [all columns are varchar]
NEW2 [empty table] [columns are of different data types]
I want to copy all data from New to New2.
What i did is,
SELECT T.*
INTO #tmp
FROM (SELECT *
FROM [dbo].[new]) AS T
then
INSERT INTO New2(col1, col2....)
SELECT *
FROM #TMP
But its not working.
Msg 242, Level 16, State 3, Line 2
The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
The statement has been terminated.
[what I want is to change the column data types of NEW table, especially the varchar to smalldatetime. So I tried this way. Any other approach is also welcome.]
Any help would be greatly appreciated.
Thank You.
Yes. Done.
What I did is,
Imported Excle data in SQL Server table with all columns in a table as varchar data type.
The problem was in excel data, the date values, somewhere was NA. So I had to replace all those NA values with null.
To check for those invalid date values in a table, I used following command.
SELECT ISDATE(COL_NAME) AS Result
SELECT ISNULL(COL_NAME) AS Result
For this, sometime you have to also check & set for the date format of SQL Server using following commands,
DBCC useroptions
SET DATEFORMAT mdy
Then all the result values I replaced them with NULL as
UPDATE TABLE SET COLUMN = NULL WHERE ISDATE(COLUMN) = 0 OR COLUMN = 'NA'
At last I updated required columns manually using simple alter commands as,
ALTER TABLE ALTER COLUMN COL_NAME <<data type>>
I also changed my dateforamat to dmy which prior was mdy.
Thank for Suraj Singh, Deepshikha for their helpful suggestions.
While inserting cast your column to smalldatetime
SET DATEFORMAT ymd
INSERT INTO New2(col1, col2....)
SELECT Col1,Col2 , CAST('2007-05-08 12:35:29' AS smalldatetime) As Col_Name,...Col3
FROM #TMP
Try as:
DECLARE #NEW TABLE([date] VARCHAR(20));
INSERT #NEW SELECT '2/8/2013 15:00' ;
select LEFT([date],2) + SUBSTRING([date],3,2) + SUBSTRING([date],5,4) + ' '+ RIGHT([date],5)+':00'
from #NEW
UPDATE #NEW SET [date] = CONVERT(CHAR(16), CONVERT(SMALLDATETIME,
LEFT([date],2) + SUBSTRING([date],3,2) + SUBSTRING([date],5,4) + ' '+ RIGHT([date],5)+':00', 120));
SELECT [date], CONVERT(SMALLDATETIME, [date]) FROM #NEW;
Try This
SET DATEFORMAT ymd
INSERT INTO destination_table(column_name)
SELECT Column_name As Aliace_name
FROM Source_table