MS Access Alter Statement: change column data type to DATETIME - sql

I have a column named as recordTime in my Access DB table table1.
This column is of TEXT type right now, and most of its value are in format as: yyyy-mm-dd hh:nn:ss, but there are also some wrong records like this: yyyy-mm- ::.
Now I would like to change the data type of this column from TEXT to DATETIME. I tried with the following query but nothing happens:
ALTER TABLE table1
ALTER COLUMN recordTime DATETIME;
Am I doing it wrong?

Try running these:
ALTER TABLE table1 ADD NewDate DATE
Then run
UPDATE table1
SET NewDate = RecordTime
WHERE RIGHT(RecordTime,4) <> '- ::'
You can then delete the RecordTime and rename NewDate.
I prefer adding a new column just in case there are any issues with the UPDATE and you can compare the 'cleaned' column and the initial data before proceeding.

Related

How to convert a string column into a date column

Imported a date column from a CSV file where there are string values are shown as
date
44705
44704
44703
I want to convert the entire column into a date format as
date
"2022-05-22"
"2022-05-21"
"2022-05-20"
I have used this script which allowed me to generate the result.
SELECT dateadd(d,44703,'1899-12-30') as date
The question is, how could I apply this script for a range of values (there are 700 rows in the table). e.g 44000 to 44705. I would like all string values to be converted as a date format.
select cast (44705-1 as smalldatetime) gives 2022-05-25 00:00
So you could just update the column using the above.
See https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=dc24abb3025e0f3796e7d978ba406be3
New fiddle with update statement, this line will update all rows, as per test.
update #test
set pdate = cast(dateadd(d,tdate-2,'1899-12-30') as smalldatetime)
To convert a string to date we can add temporary date column and fill it and delete old column and rename new one to old one
alter table TableName add NewColumnName date null; --create temporary column
update TableName set NewColumnName =dateadd(d,cast(cast([date] as float) as int)-2,'1899-12-30') --fill it
alter table TableName drop column [date]--delete old column
EXEC sp_RENAME 'TableName.NewColumnName' , 'date', 'COLUMN'--rename new one to old one

How to add column to database with default

I have a database that I'm trying to add a column to. This column should hold information of the type timestamp, and I want every row to have the same timestamp (the current time) when I'm done.
I currently have tried:
cursor.execute('''ALTER TABLE my_table ADD COLUMN time timestamp DEFAULT ?''', (datetime.datetime.utcnow(),))
Which results in sqlite3.OperationalError: near "?": syntax error.
So then I tried:
cursor.execute(f'''ALTER TABLE my_table ADD COLUMN time timestamp DEFAULT {datetime.datetime.utcnow()}''')
Which results in sqlite3.OperationalError: near "-": syntax error.
Also, doing
cursor.execute(f'''ALTER TABLE my_table ADD COLUMN time timestamp DEFAULT CURRENT_TIMESTAMP''')
results in sqlite3.OperationalError: Cannot add a column with non-constant default.
How can I add the new column and set the values in that column? (Either through DEFAULT, or some other mechanism.)
SQLite does not allow adding a new column with a non-constant value. So this:
alter table my_table add column my_time timestamp default current_timestamp;
... generates error:
Cannot add a column with non-constant default
A simple option would be to recreate the table. Assuming that you have single column called id, that would look like:
create table my_table_new(
id int primary key,
my_time timestamp default current_timestamp
);
insert into my_table_new(id) select id from my_table;
drop table my_table; -- back it up first !
alter table my_table_new rename to my_table;
You can first add the new column and then update every existing row in the table to the desired value:
ALTER TABLE my_table ADD COLUMN time;
UPDATE my_table SET time = CURRENT_TIMESTAMP;

Display Now date and Time in SQl table column

I want to be able to have todays date and time now in a table column
If my table is say Table1, basically it should display the time and date when
SELECT * FROM Table1 is run.
I've tried the following but they just show the time from the moment in time I assign the value to column
ALTER TABLE Table1
ADD TodaysDate DateTime NOT NULL DEFAULT GETDATE()
and
ALTER TABLE Table1
ADD TodaysDate DateTime
UPDATE Table1
SET TodaysDate = GETDATE()
Hope this is clear. any help is appreciated.
Thanks
In SQL Server you can use a computed column:
alter table table1 add TodaysDate as (cast(getdate() as date));
(use just getdate() for the date and time)
This adds a "virtual" column that gets calculated every time it is referenced. The use of such a thing is unclear. Well, I could imagine that if you are exporting the data to a file or another application, then it could have some use for this to be built-in.
I hope this clarifies your requirement.
The SQL Server columns with default values stores the values inside the table. When you select the values from table, the stored date time will be displayed.
There are 2 options I see without adding the column to the table itself.
You can use SELECT *, GETDATE() as TodaysDate FROM Table1
You can create a view on top of Table 1 with additional column like
CREATE VIEW vw_Table1
AS
SELECT *, GETDATE() as TodaysDate FROM dbo.Table1
then you can query the view like you mentioned (without column list)
SELECT * FROM vw_Table1
This will give you the date and time from the moment of the execution of the query.

Changing the data type "varchar'' of a column to "DATE" in SQL/ORACLE

I have a table in a database created in oracle 10G. It contains a column of type 'VARCHAR' and stores date as string in this format-> 'dd-mon-yyyy' eg: '12-aug-2008'. Now I want to change the datatype of this column from VARCHAR to DATE. but when i perfrom this query->
ALTER TABLE sales_order
MODIFY COLUMN delivery_date DATE;
I get following error
ORA-00905: missing keyword
I have also tried :
ALTER TABLE sales_order
ALTER COLUMN delivery_date DATE;
I got the error :
ORA-01735: invalid ALTER TABLE option
However when i try to add a fresh column with DATE datatype it works fine.
example :
ALTER TABLE sales_order
ADD delivery DATE;
So, can anybody suggest me a way to change the datatype without deleting the column and its data.
It's the first one, with a slight modification:
ALTER TABLE sales_order MODIFY (delivery_date DATE);
But I'm not sure that will work for those particular datatypes and it also may not work depending on the current data.
You may find it necessary in that case to:
create a new column X of date type.
populate X based on the old column (may need several passes of data fix-ups to work).
delete old column.
rename X to old column name.
Although its a pretty old question, I'll put my solution here for people seeking for a solution:
Here's my solution and it works perfectly.
ALTER TABLE `sales_order` CHANGE `delivery_date` `delivery_date` DATE;
Thank you
modify a column then syntax is:-
alter table table_name modify column_name datatype;
but when you modify the column datatype column must be empty
Thanks for the hints! This got it for me.
alter table Table_Name
Alter column Column_Name datatype
GO
I too was needing to change from a VARCHAR to a date. I am working in SQL 2008 R2. I have found that if I bring in dates as a char or varchar and then change the type to date or datetime, I can catch time/date problems more easily.
THIS STATEMENT WILL FAIL IF YOUR DATA HAS ANY BAD DATES. (I break the date down into sections to find the bad date so I can correct and then I can alter the column type.)
Alternatively, you could create a new column, in which the data type is DATE. then pass the data in your varchar as a date .then drop your initial column and finally rename your new column to what it was initially...code below.
ALTER TABLE my_table ADD (new_col DATE);
UPDATE my_table SET new_col=TO_DATE(old_col,'MM/DD/YYYY');
ALTER TABLE my_table DROP (old_col);
ALTER TABLE my_table RENAME COLUMN new_col TO old_col;
alter table employee add (DOB varchar(10));
if you add a column with datatype varchar and if you want to modify the datatype of DOB then you can use this command ->
alter table employee modify(DOB date);
Now the table is modified.

How can I copy data from one column to another in the same table?

Is it possible to copy data from column A to column B for all records in a table in SQL?
How about this
UPDATE table SET columnB = columnA;
This will update every row.
UPDATE table_name SET
destination_column_name=orig_column_name
WHERE condition_if_necessary
This will update all the rows in that columns if safe mode is not enabled.
UPDATE table SET columnB = columnA;
If safe mode is enabled then you will need to use a where clause.
I use primary key as greater than 0 basically all will be updated
UPDATE table SET columnB = columnA where table.column>0;
If you want to copy a column to another column with a different data type in PostgresSQL, you must cast/convert to the data type first, otherwise it will return
Query 1 ERROR: ERROR: column "test_date" is of type timestamp without
time zone but expression is of type character varying LINE 1: update
table_name set test_date = date_string_col
^ HINT: You will need to rewrite or cast the expression.
An example of converting varchar to timestamp:
update table_name set timestamp_col = date_string_col::TIMESTAMP;
An example of converting varchar to int:
update table_name set int_column = string_col::INTEGER;
but any column type(except file or the similar) can be copied to string(character varying) without cast the type.