sql Alter table: create a column base on datediff between 2 columns - sql

I want to creat a computed column based on datediff function between 2 existing columns (date1 and date2). (in days)
date1 and date2 are sql DATE type.
What I tried without sucess :
ALTER TABLE my_table ADD lenght AS datediff('dd', date1, date2)
Thank you for helping.

A GENERATED column is automatically updated when the values it refers to in other columns change. The correct syntax is:
ALTER TABLE my_table ADD length INT GENERATED ALWAYS AS (DATEDIFF('day', date1, date2))

ALTER TABLE my_table ADD lenght AS int;
UPDATE my_table SET lenght = DateDiff('dd', date1, date2);
-- Don't forget to add a trigger that fires on updated and inserted rows that will keep the value of lenght valid if the date1 or date2 changes

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 convert two types of dates format into one date format in SQL?

I have three table in the database two of them contain dates however the dates are in two format, first 20-02-2011 and second is 25/09/2018. Let say each table have 10000 records and mixed with these two types of dates format. This why I why I create the column like --- (Transaction_Date, Varchar(10) Not Null)
I tried convert (Varchar(10),Transaction_Date,105)
and also tried replace(convert(varchar(10),Transaction_Date,105),'/','-')
However date and year functions are still not working.
Please suggest a possible way.
How about this?
select replace(date, replace(Transaction_Date, '/', '-'), 105)
That is: (1) convert to a date and (2) replace the slash before converting.
You need to remember about your culture. Saved format vs server culture. But this is very possible
select Cast('2-22-2011' as datetime) f1,
Cast('2/22/2011' as datetime) f2
I other words just use Cast
select cast(Transaction_Date as datetime) . . .
But you should as soon as possible get rid of columns that saves date as string and create new date/time column, and insert your date values there
alter table tbl add column temp datetime
update tbl set temp = Cast(Transaction_Date as datetime)
alter table tbl drop column Transaction_Date
alter table tbl add column Transaction_Date datetime
update tbl set Transaction_Date = temp
alter table tbl drop column temp

Add a column with the current timestamp to a table in Hive

I'm trying to add a column called tstamp to a table that I've created. The column is to have the current timestamp in the format 'yyyy-MM-dd' populating each row.
I initially created the table from another table (table1) using the statement:
create location2.table2
as (select *
from location1.table1
);
I then used the alter table statement to add a field called tstamp to table2 using the code:
alter table location2.table2
add columns (tstamp date)
and I can see that this has successfully added a column to table2 named tstamp and populated each row of this table as null. I am now trying to insert the current date into every row in the field tstamp but am struggling to do so. I've tried using the insert into statement as:
insert into location2.table2 (tstamp)
values (to_date(current_timestamp()))
but get the error "Expression of type TOK_FUNCTION not supported in insert/values". I then also tried to add just a string and replaced the function with '2019-07-25'. Doing this added a new row to my table with null values in every column except tstamp which had a value '2019-07-25'. I'm now confused as it appears my approach was not the right one for the problem and am unsure where to go from here. Any help would be greatly appreciated.
create location2.table2 as (select current_date as tstamp,* from location1.table1 );

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.

Computed Column Specification in SQL Server - Time Difference in hours or minutes

Is there a way to have a column in the table which auto-calculates the time difference between the start date and the end date as such?
(datediff(hour,[StartTime],[EndTime]))
ALTER TABLE yourTable
ADD yourColumn AS (datediff(hour,[StartTime],[EndTime]))
SQLFiddle DEMO
EDIT:
That was the syntax for alter table, off-course you can also define it during table creation
CREATE TABLE tbl1
(
startDate DATETIME,
enddate DATETIME,
diffCol AS (datediff(hour,startDate,enddate))
);
SSMS also have an option in table designer to add formula for computed columns
Assuming both StartTime and EndTime are columns on the same row of your table, you can use a computed column:
ALTER TABLE MyTable ADD TimeDiffHours AS DateDiff(hour,[StartTime],[EndTime]);