I have a question related to the conversion of varchar to datetime.
This topic was covered already in the thread
SQL Server Convert Varchar to Datetime
but I would like to advance it bit further.
I have performed BULK INSERT into predefined tables where VARCHAR(255)
is the destination. I have a table dbo.USR_02_ALL_RAW and the field GLTGB which
holds strings in the following format: 07/16/2016.
I can convert it as a single string by the following code:
DECLARE #Date varchar(255)
set #Date= '07/16/2016'
SELECT CONVERT(datetime,RIGHT(#Date,4)+LEFT(#Date,2)+SUBSTRING(#Date,4,2))
and it gives me a result:
2016-07-16 00:00:00.000
However I would like to pass to the code the whole field GLTGB from the table
dbo.USR_02_ALL_RAW, convert it from VARCHAR into DATETIME and update the field GLTGB with these results.(converting the whole field from varchar to datetime)
Thank you!
First clear this, you want to Bulk insert or Bulk update. Since you already have a column GLTGB. If you want to update the value only.
update tab set GLTGB =
CONVERT(datetime,RIGHT(GLTGB,4)+LEFT(GLTGB,2)+SUBSTRING(GLTGB,4,2))
Or
If you want to update the field from varchar to datetime. Then process is little bit lengthy.
Alter table tab add newcol datetime --- Add new datetime type column
update tab set newcol =
CONVERT(datetime,RIGHT(GLTGB,4)+LEFT(GLTGB,2)+SUBSTRING(GLTGB,4,2)) --- update value in new column
Alter table tab drop column GLTGB --- drop GLGTB column
Alter table tab add GLGTB datetime --- add GLGTB column as datetime type
update tab set GLGTB = newcol --- update value from GLGTB from newcol
Alter table tab drop column newcol ---- remove unnecessary newcol
If you convert a value to datetime, then update the same database column it came from with the value then, since that column is still varchar, SQL will have to convert the value back to varchar again in order to store it. So you can't achieve anything useful with that kind of simple approach.
f you want to actually change the data type of the column, and also convert all the values, then I think you need to go through the following process:
1) Create a new varchar column in your table (which will be temporary)
2) copy all the data values from the GLTGB column into the new column (using an UPDATE statement)
3) Drop the GLTGB column
4) Re-create it with the same name but with datetime type
5) Use an UPDATE statement to re-populate the new GLTGB column from your temporary column
6) Finally, drop the temporary column
There may be a simpler way but that seems like the obvious process.
You can use the following code for updating but before that, you need to change the data type of your field to DateTime
update dbo.USR_02_ALL_RAW
set GLTGB=cast(CONVERT(datetime,RIGHT(#Date,4)+LEFT(#Date,2)+SUBSTRING(#Date,4,2)) as datetime)
Related
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
I have a column datedocumented in the format YYYYMMDD and of the datatype nvarchar. I want to change the data type to datetime and update the column name exdatedocumented and alter the table using ALTER .can anyone help in this.I have tried something like this
update dbo.table2
set [DateDocumented] = convert(datetime,CAST([DateDocumented] as datetime),130)
I ended up getting error
Msg 242, Level 16, State 3, Line 1
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated
.
You should be able to just change the column type:
alter dbo.table2 alter column DateDocumented datetime;
Your column is in a format suitable for conversion. If you wanted to use default formats instead, just do:
update table dbo.table2
set [DateDocumented] = convert(datetime, CAST([DateDocumented] as datetime));
This should also allow the column to be converted to a datetime.
1st change that column name then alter table
sp_RENAME 'dbo.table2.datedocumented', 'exdatedocumented' , 'COLUMN'
go
ALTER TABLE dbo.table2
ALTER COLUMN exdatedocumented datetime;
It seems we have two things going on here. Changing the type for a column. And changing the name for a column. Let's try to keep these separate so not to confuse things. I will adress the changing of type (from varchar to datetime):
First of all: Why datetime? Why note datetime2 (with whatever fractions of seconds you want, for instance datetime2(0))? The new types for date and time has been around for 10 years now!
Anyhow, you apparently have values in your table which are not valid dates! First thing you need to do is to find those rows and handle them. Lets say that you will change to datetime2(0), if not, then just change below to datetime instead:
SELECT *
FROM dbo.Table2
WHERE TRY_CAST(DateDocumented AS datetime2(0)) IS NULL
I have a SQL Server database and I'd like to change column types to reduce it's size:
I have a string Name Varchar(100) and want to convert it to Varchar(50) AND I have to move data to it (data will fit into varchar(50))
I have a Varchar(30) that represents time as epoch time (eg. 1508752574). I want to change the type to Datetime and convert data form Varchar(30) to Datetime and then put it in Datetime
Can I do it without losing data?
Point 1
ALTER TABLE dbo.table_name ALTER COLUMN name VARCHAR(50);
Point 2
You would need to add another column of type Datetime and update the column with the Datetime equivalent of the epoch_time_col.
ALTER TABLE dbo.table_name ADD epoch_time_dt DATETIME NULL;
UPDATE dbo.table_name SET epoch_time_dt = DATEADD(SECOND, epoch_time_col, '19700101');
If you need, you can then drop the old column
ALTER TABLE dbo.table_name DROP COLUMN epoch_time_col ;
Create new columns:
Alter table MyTable
add NewColumn1 varchar(50);
Alter table MyTable
add NewColumn2 datetime;
Fill with data:
update MyTable
set NewColumn1 = left(Name,50),
NewColumn2 = dateadd(s, epochcol1, '19700101');
You can then drop the old columns and rename the new ones
I don't see any loss of data issue..
I have a string Name Varchar(100) and want to convert it to Varchar(50) AND I have to move data to it (data will fit varchar(50))
There will be no data loss,if your data fits in varchar(50) data type,if the data doesn't fit the insert will fail and you can rectify that
Also i don't see any issue with data loss in converting your epoch value to datetime with below approach,since you are just adding seconds
Select
dateadd(S, [unixtime], '1970-01-01')
From [Table]
I have a column called MyYear that is of type datetime. It only stores the year though, so I want to change it to smallint.
When I try to run this:
ALTER TABLE MyTable
ALTER COLUMN MyYear smallint
I get this error:
Implicit conversion from data type datetime to smallint is not
allowed. Use the CONVERT function to run this query.
When I run this:
UPDATE MyTable
set MyYear=YEAR(MyYear)
It does something funky and sets all the years to 1905.
I am using SQL Server.
You cannot convert a DATETIME to a SMALLINT, you will need to:
ALTER TABLE MyTable
ADD MyActualYear SMALLINT
GO
UPDATE MyTable SET MyActualYear = CAST(YEAR(MyYear) AS SMALLINT)
GO
ALTER TABLE MyTable
DROP COLUMN MyYear
GO
EXEC sp_RENAME 'MyTable.[MyActualYear]' , 'MyYear', 'COLUMN'
GO
i.e. add a new temporary column, update it with the value you need, drop the old column and then rename the temp column with the original name.
If you have indexes on this column, you may want to bear in mind any impact this might have.
I have a datetime column that I need to alter to be a varchar column.
Using the statement below, the strings produced have this format: "Jan 18 2010 5:28PM"
ALTER TABLE Thinger
ALTER COLUMN LastUpdateDate varchar(16) NOT NULL
I would like strings produced to have a yyyyMMdd format (giving 20100118) instead. Is there a way to do this?
Thanks
Bad, Bad idea...never ever store dates in varchar columns, now you will get garbage in there in different formats
Also why varchar(16) when you want yyyyMMdd?
if you want the output to be in a different format do it in the presentation layer or use convert
SELECT CONVERT(CHAR(8),GETDATE(),112)
now if you really want to do what you say you want to do
run your script and then do
UPDATE Table
SET LastUpdateDate = CONVERT(CHAR(8),(CONVERT(DATETIME,CONVERT(varchar,LastUpdateDate))),112)
But again..bad bad bad idea
Also the next version of SQL Server will make formatting a lot easier see: Format function in SQL Server Denali CTP3
Try this script:
ALTER TABLE Thinger ADD LastUpdateDateText VARCHAR(16) NOT NULL
GO
UPDATE Thinger SET LastUpdateDateText = CONVERT(VARCHAR(8), LastUpdateDate, 112)
GO
ALTER TABLE Thinger DROP COLUMN LastUpdateDate
GO
sp_RENAME 'Thinger.LastUpdateDateText' , 'LastUpdateDate', 'COLUMN'
GO