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

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]);

Related

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

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

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

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 do I get the current date in SQL when entering data to a microsoft database?

I am using Microsoft SQL Server and SQL Server Management Studio.
I have a column called dateApplied which has a constraint like this:
[dateApplied] >= getDate()
When I enter a row the date is automatically added the row.
My problem is when I use the SELECT function, the dateApplied column is automatically changed to the current date and time in which the SELECT statement is called.
How do I prevent this from happening?
Thanks
Peter
I suppose you're using a computed column, like:
create table t1
(
id int
, date_col as getdate()
)
Try a default constraint instead:
create table t1
(
id int
, date_col datetime constraint DF_T1_DateCol default getdate() not null
)
A computed column is calculated whenever you run a query. A default constraint is only generated when the row is first inserted.