Auto-computed column in SQL Server 2012 - sql

Is it possible for a column in to be auto-calculated by SQL Server 2012 itself?
For example: I have three columns START_DATE, END_DATE and DURATION.
I want to get the duration by doing this :
DURATION = END_DATE - START_DATE
So I get the duration in number of days.
Is it possible for SQL Server 2012 to do it automatically on record creation ?

Yes, sure - just define Duration to be a computed column:
ALTER TABLE dbo.YourTable
ADD Duration AS DATEDIFF(DAY, START_DATE, END_DATE) PERSISTED
and off you go. Now Duration will always show the difference (in days) between these two other columns. The value computed will be stored along side your other column values, if you use the PERSISTED keyword. This column will be updated if any of the two "dependent" columns changes, too.
Update: if you want to get the difference between a date and today, you can use
ALTER TABLE dbo.YourTable
ADD Duration AS DATEDIFF(DAY, START_DATE, GETDATE())
but unfortunately, since the GETDATE() function is non-deterministic (after all - it's return value changes every time you call it), you cannot use the PERSISTED keyword. This means: every time you access the column (ask for its value), the calculation will be done again.

In your Table Design, enter any of these in (Formula) under Computed Column Specification for your required result.
For Date Difference:
CAST(job_end - job_start) AS TIME(0))
For Time Duration:
SUBSTRING(CONVERT(VARCHAR(20),(END_DATE-START_DATE),120),12,8)
Similarly you can compute for Second, Minute, Hour, Month, Year differences.
Syntax for using DATEDIFF:
DATEDIFF ( datepart , startdate , enddate )
For your Reference:
DATEDIFF(SECOND, GETDATE(), GETDATE() + 1) AS SecondDifference
DATEDIFF(MINUTE, GETDATE(), GETDATE() + 1) AS MinuteDifference
DATEDIFF(HOUR, GETDATE(), GETDATE() + 1) AS HourDifference
DATEDIFF(DAY, GETDATE(), GETDATE() + 1) AS DayDifference
DATEDIFF(WEEK, GETDATE(), GETDATE() + 1) AS WeekDifference

Related

Searching data for current date in SQL Server

Why is the first query taking less time than the second one in SQL Server?
This query takes 4 seconds to complete:
select *
from salesinvmaster
where day(salesdate) = day(getdate()) and
month(salesdate) = month(getdate()) and
year(salesdate) = year(getdate())
This query takes 10 seconds:
select *
from salesinvmaster
where salesdate between '2017-11-01 00:00:00' and '2017-11-01 23:59:59'
The two queries are different, because today is some day in December, not November 1st.
My guess is that you do not have an index on the salesdate column, and that the first query is returning fewer rows -- hence, it looks faster. For the record, I would recommend writing the logic as one of the following:
where convert(date, salesdate) = convert(date, getdate())
where salesdate >= convert(date, getdate()) and
salesdate < dateadd(day, 1, convert(date, getdate()))
Note that SQL Server does use an index for the conversion of a date/time value to a date. This is one of the rare (only?) times when a function does not prevent the use of an index.
As for the second method, it dispenses with the need to include the time component of the values.
Check the Exeuction plan for the query i think We've got implicit conversions on the date! check this

Get date of 3 days ago

I have SQL script that selects everything from current day.
SELECT [ClientID] from [logs] where Date > CONVERT (date, SYSDATETIME())
Date is type of DateTime.
How to get everything within last 3 days? I suppose I need subtract 3 days from function SYSDATETIME() result, but how?
SELECT [ClientID] from [logs] where Date > DATEADD(day, -3, CONVERT (date, SYSDATETIME()))
Use GETDATE() : Yes, it gets date from system!
Returns the current database system timestamp as a datetime value
without the database time zone offset. This value is derived from the
operating system of the computer on which the instance of SQL Server
is running.
Query:
SELECT [ClientID] from [logs] where ( Date > GETDATE() - 3)
More Reference:
GETDATE Detailed Documentation
For mysql use this:
SELECT DATE_ADD(CURRENT_DATE, INTERVAL - 3 DAY);
Use BETWEEN
SELECT ClientID
FROM logs
WHERE Date BETWEEN SYSDATETIME() AND SYSDATETIME() - 3
Using BETWEEN is nice. I also prefer the DATEADD function. But be aware of the fact that the SYSDATETIME function (or I would us GETDATE()) also includes the time which would mean that events before the current time but within the three day period may not be included. You may have to convert both sides to a date instead of datetime.
SELECT [ClientID] from [logs] where Date > DATEADD(day, -3, SYSDATETIME())
In my case:
select * from Table where row > now() - INTERVAL 3 day;
So you can fetch all of 3 days ago!

How to compare current time to retrieve record stored in SQL

I have a database in which one of the column name is 'date' I need to count the number of entries that have been added with today's date after 09.00.00
So far I have done this..I am wondering where do I specify the time '09.00.00'
SELECT COUNT(*) AS total from DATABASENAME
WHERE date >= Convert(datetime, Convert(int, GetDate()))
Here's code that should work. You're essentially converting a datetime to a date to remove the time, then back to a datetime and adding in the hour that you want.
SELECT COUNT(*) AS Total
FROM TableName
WHERE Date >= DATEADD(HOUR, 9, CONVERT(DATETIME, CONVERT(DATE, GETDATE())))
Well is the date column store date and time or date only, if it is date only you need to add the time also in the column and also avoid converting data type in where condition try the above query with a parameter variable

SQL - Query condition for future date time

Im having trouble with this query. I want to not select records that have passed the SYSTIME for the current date but display records for future dates even if they have passed the current SYSTIME
SELECT *
FROM TABLE
WHERE DATE>= CONVERT(date, SYSDATETIME())
AND STARTTIME > CONVERT(time, SYSDATETIME())
This is the query. I know why it doesnt work but I can't think of a way to do what I stated above.
SELECT *
FROM TABLE
WHERE
(
(DATE = CONVERT(date, SYSDATETIME()
AND STARTTIME > CONVERT(time, SYSDATETIME()
)
OR Date > sysdatetime()
)
You need an or condition since date time are in different fields you must first resolve today's date and time and then all future dates regardless of time.
This depends a lot on what the original data types are. Let's assume they are date, time, or datetime.
If you want anything in the future, then this works:
where [date] + starttime > sysdatetime()
If you want just future dates then try:
where [date] > cast(sysdatetime() as date)
The latter is how I interpret your question, but I'm not 100% sure that my interpretation is correct.

Get tomorrows date

I am trying to get tomorrows date in a sql statement for a date comparison but it is not working.
Below is my code:
select *
from tblcalendarentries
where convert(varchar,tblcalendarentries.[Start Time],101)
= convert(varchar, GETDATE() +1, 101)
To get tomorrows date you can use the below code that will add 1 day to the current system date:
SELECT DATEADD(day, 1, GETDATE())
GETDATE()
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.
DATEADD(datepart , number , date)
Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date.
So adding this to your code in the WHERE clause:
WHERE CONVERT(VARCHAR, tblcalendarentries.[Start Time], 101) =
CONVERT(VARCHAR, DATEADD(DAY, 1, GETDATE()), 101);
First off, GETDATE() will get you today's date in the following format:
2013-04-16 10:10:02.047
Then using DATEADD(), allows you to add (or subtract if required) a date or time interval from a specified date. So the interval could be: year, month, day, hour, minute etc.
Working with Timezones?
If you are working with systems that cross timezones, you may also want to consider using GETUTCDATE():
GETUTCDATE()
Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.
Try the below:
SELECT GETDATE() + 1
This adds one day to current date
Specify size of varchar in convert()
where convert(varchar(11),tblcalendarentries.[Start Time],101) = convert(varchar(11), GETDATE() +1, 101)
I would write:
where
DATEADD(day,DATEDIFF(day,0,tblcalendarentries.[Start Time]),0) =
DATEADD(day,DATEDIFF(day,0,GETDATE()),1)
This avoids converting dates to strings entirely, whilst also removing the time portion from both values.