Change Date format during SQL - sql

I am moving data to a new database and need to so some formatting during the move to try and save me time.
The current DB saves the date as YYYYMMDD and the new DB wants it in mm/dd/yyyy. Can I do this during the move or will I have to format after?
Thank you all!

You cold use the format function . So I am not sure how you are getting the data to sql 2014 but once the data is there you could use this command.
This is an example selecting from a table that has a date and altering its format .
use AdventureWorks2012
go
select modifieddate as 'original format', FORMAT ( modifieddate, 'd', 'en-US' ) AS 'New format mm/dd/yy'
from [Sales].[SalesOrderDetail]
Query Result
If your data is not format and its just a string you could use the format command to add the separators .
This code create a table with a date as an INT, the selects the data and formats it as a data time into another table .
CREATE TABLE Test_TimeString (Timeint int)
GO
INSERT INTO Test_TimeString VALUES(04242016)
GO
CREATE TABLE Test_Time (Timedate DATETIME)
GO
INSERT INTO Test_Time
SELECT FORMAT(Timeint,'##/##/####')
FROM Test_TimeString
SELECT * FROM Test_Time

Related

manipulate data of a column

I have a CSV file containing about 30m rows with a column that has a date type. But the problem is with its format. PSQL supports '-' delimiters for timestamp but my dates are using '/'. For example, the date should be '2021-02-01 00:00:00' but my date format is '2021/02/01 00:00:00'. Also, I can not open the CSV file and change it manually due to its large size. I am trying to import my data into a temporary table to replace the '/' with '-' and then inserting them to a new table and I am using the following command(it is not the real table and it is just an example):
CREATE TABLE TMP(
dt VARCHAR
)
CREATE TABLE other_tmp(
dt TIMESTAMP
)
INSERT INTO TMP VALUES('2020/01/02 22:33:11');
INSERT INTO other_tmp(dt)
SELECT dt,
REPLACE(dt, '/', '-')
FROM TMP
I get an error with replace function when I want to run it.
Does anybody know that how can I solve this problem? Or even is it possible to manipulate the column in the original table?
Try this,
In this case, your column "dt" is of type timestamp without time zone but the expression is of type text. So the text should cast to timestamp as below.
CREATE TABLE IF NOT EXISTS TMP
(
dt VARCHAR
);
CREATE TABLE IF NOT EXISTS other_tmp
(
dt TIMESTAMP
);
INSERT INTO TMP
VALUES ('2020/01/02 22:33:11'::TIMESTAMP);
INSERT INTO other_tmp(dt)
SELECT REPLACE(dt, '/', '-')::TIMESTAMP AS dt
FROM TMP;
Your first error is that you have two columns in the SELECT list, but only one column in the INSERT target.
To convert a string to a timestamp, use to_timstamp()
insert into other_tmp(dt)
select to_timestamp(dt, 'yyyy/mm/dd hh24:mi:ss')
from tmp;
Online example

Sql in Snowflake changing date from 106(13-APR-2020) to 105(13-04-2020)

So I have a couple date fields in a table that are formatted as (DD-MON-YYYY) and I need to convert them to (DD-MM-YYYY) The field itself is already a VARCHAR. In Snowflake, how would I make this change. Here is what I have done so far.
select to_date(end_date, 'dd-mm-yyyy') from
error: Can't parse '31-JAN-2020' as date with format 'dd-mm-yyyy'
An easy way for you to approach this is to convert your string to a date, and then back to a string in the new format, an example follows:
--create an example table to test
CREATE TEMPORARY TABLE xyz (my_dt_string VARCHAR(100));
--insert a couple records
INSERT INTO xyz VALUES ('31-JAN-2020'), ('13-APR-2020');
--test a conversion, from string to date back to string
SELECT my_dt_string,
TO_CHAR(TO_DATE(my_dt_string, 'dd-mon-yyyy'), 'dd-mm-yyyy') converted
FROM xyz;
--looks good? run the following
UPDATE xyz
SET my_dt_string = TO_CHAR(TO_DATE(my_dt_string, 'dd-mon-yyyy'), 'dd-mm-yyyy');
--take a look
select * from xyz;
I hope this helps...Rich
The to_date() function provides you the ability to convert a VARCHAR field to a DATE field, not specify the format of the date. So, you'd want to run this:
SELECT TO_DATE(end_date, 'DD-MON-YYYY');
This will output the date as a date. If you want to specify how you see a date, you have 2 choices:
First, convert it back to a VARCHAR in your preferred format:
SELECT TO_VARCHAR(TO_DATE(end_date, 'DD-MON-YYYY'),'DD-MM-YYYY');
Second, change your session parameter DATE_OUTPUT_FORMAT to be the format you'd like to see dates displayed:
ALTER SESSION SET DATE_OUTPUT_FORMAT = 'DD-MM-YYYY';
This could also be done for a user, rather than a session using:
ALTER USER SET DATE_OUTPUT_FORMAT = 'DD-MM-YYYY';

How to insert date values into table

How can I insert into table with different input using / ,with date datatype?
insert into run(id,name,dob)values(&id,'&name',[what should I write here?]);
I'm using oracle 10g.
Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:
TO_DATE('<date_literal>', '<format_model>')
For example,
SQL> CREATE TABLE t(dob DATE);
Table created.
SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));
1 row created.
SQL> COMMIT;
Commit complete.
SQL> SELECT * FROM t;
DOB
----------
17/12/2015
A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.
For example,
SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');
1 row created.
date must be insert with two apostrophes'
As example if the date is 2018/10/20. It can insert from these query
Query -
insert into run(id,name,dob)values(&id,'&name','2018-10-20')
let suppose we create a table Transactions using SQl server management studio
txn_id int,
txn_type_id varchar(200),
Account_id int,
Amount int,
tDate date
);
with date datatype we can insert values in simple format: 'yyyy-mm-dd'
INSERT INTO transactions (txn_id,txn_type_id,Account_id,Amount,tDate)
VALUES (978, 'DBT', 103, 100, '2004-01-22');
Moreover we can have differet time formats like
DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
insert into run(id,name,dob)values(&id,'&name',[what should I write
here?]);
insert into run(id,name,dob)values(&id,'&name',TO_DATE('&dob','YYYY-MM-DD'));
You can also use the "timestamp" data type where it just needs "dd-mm-yyyy"
Like:
insert into emp values('12-12-2012');
considering there is just one column in the table...
You can adjust the insertion values according to your table.
I simply wrote an embedded SQL program to write a new record with date fields.
It was by far best and shortest without any errors I was able to reach my requirement.
w_dob = %char(%date(*date));
exec sql insert into Tablename (ID_Number ,
AmendmentNo ,
OverrideDate ,
Operator ,
Text_ID ,
Policy_Company,
Policy_Number ,
Override ,
CREATE_USER )
values ( '801010',
1,
:w_dob,
'MYUSER',
' ',
'01',
'6535435023150',
'1',
'myuser');
To insert the current date you can just use this GETDATE() function.
insert into run(id,name,dob) values(&id,'&name',GETDATE());
you can also use CURRENT_TIMESTAMP() function to insert current date and time.

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

bulk insert datetime data

I try to bulk insert some datetime values in this format:
31/12/2005 00:00:00
using something like this:
create table Seed
(
StartDate datetime not null
)
BULK INSERT Seed
FROM 'd:\dump\Seed.txt'
WITH
(
firstrow=2,
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
But I get this:
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row
I know how to define a codepage but which? Is there a simple solution?
Thanks.
Christian
What is the default language for the user logged in to the SQL instance while running this T-SQL? The date format you specified 31/12/2005 00:00:00 looks to be British and perhaps your default language is US_English.
Try running this T-SQL to determine your current language:
SELECT ##language, ##langid
If it's US_English, then your date format should be mm/dd/yyyy hh:mm:ss
To keep your example alive, try changing your default language for the current user by doing the following:
--Get the current language setting for connected user
SELECT ##LANGUAGE,##LANGID
--Get information about all languages
EXEC sys.sp_helplanguage
--Get the name of the current user
DECLARE #sysuser NVARCHAR(30)
SET #sysuser = SYSTEM_USER
PRINT #sysuser
EXEC sp_defaultlanguage #sysuser, 'british' --satisfying your example date
After you have changed the default language, reconnect your query window and you should be now utilizing the new default language.
To get back to the previous language setting, just EXEC sp_defaultlanguage again with the language setting you previously had.
Hopefully that works!
SQL Server is not going to convert the DD/MM/YYYY date format correctly. You'll need to either reformat your input file as MM/DD/YYYY or insert into a char/varchar datatype and then manipulate the string into the correct format for another datetime column. For example:
create table TempSeed
(
StartDate varchar(50) not null
)
BULK INSERT TempSeed
FROM 'd:\dump\Seed.txt'
WITH
(
firstrow=2,
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
create table Seed
(
StartDate datetime not null
)
insert into Seed
(StartDate)
select CAST(substring(ts.StartDate,4,3) + stuff(ts.StartDate,4,3,'') as datetime)
from TempSeed ts