Convert varchar column to date - sql

I have one column LogDate which is varchar(2000) type. I want this column as date type. Current table format 2014-03-31 09:13:03.000.
How can I do that?

I presume you are using SQL Server:
declare #LogDate varchar(2000)
set #LogDate = '2014-03-31 09:13:03.000'
select convert (datetime, #LogDate, 21)
Full table query at: http://sqlfiddle.com/#!3/58a3f/1/0

If all the records in the table having data in correct format(i.e all are date only, no characters) then you can directly alter the column data type to DATE type:
ALTER TABLE <table name> ALTER COLUMN LogDate date

Related

SQL Server: best way to insert "mm/dd/yyyy" into a "date" or "datatime2" column?

I have a bunch of values in the form of mm/dd/yyyy stored in a CSV. An example is 06/26/2017. What I found was that I could NOT insert it into a column declared as date or datetime2 type. What I CAN do is to modify that (empty) column to varchar first, then insert.
However at this point, after insertion as varchars, how can I convert this column to "date" or "datatime2"?
Attempting to set system-wide format doesn't work:
sql> SET DATEFORMAT 'mm/dd/yyyy'
[2019-03-31 09:42:04] [S0001][2741] SET DATEFORMAT date order 'mm/dd/yyyy' is invalid.
If the column's data type is date then convert the string to date with:
convert(date, '03/31/2019', 101)
and then insert it.
See the demo.
Read more about convert()
Edit:
Create a varchar column and a date column. Insert the values inside the varchar column and when the process finishes, update the date column by converting each value to a date, like:
UPDATE tablename
SET datecolumn = convert(date, varcharcolumn, 101)
After that you can remove the varchar column.

How to change column datatype in SQL Server and convert previous type without losing data

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]

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'

T-SQL computed date column

I have a table, in TSQL, with a field containing data in YYYYMMDD format saved as varchar(50);
I want to add a date type column to the table for each of the corresponding records in this field.
Any ideas?
Assuming that you have stored correct format of date in your field (eg you don't have '20121433'), this script should works for you:
ALTER TABLE your_table
ADD your_field_Date DATETIME
UPDATE your_table
SET your_field_Date = CONVERT(DATETIME, your_field_varchar, 112)
ALTER TABLE your_table DROP COLUMN your_field_varchar

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'