Monday, October 8, 2012

Auto Increase the data in the column of a Database

For Example, there is a Employee Table which has the column No_Of_Days_Worked.

Requirement is to increase the value of the column No_Of_Days_Worked by 1 in the database

2 Approaches can be used.

Approach 1:

Use the update statement and run the update statement as a daily job
UPDATE Employee_computedcol
SET No_Of_Days_Worked = No_Of_Days_Worked + 1
Approach 2:
Using  the computed column

CREATE TABLE Employee_computedcol (
EmpID INT IDENTITY(1,1) PRIMARY KEY,EmpName nvarchar(128) NOT NULL UNIQUE,DOJ DATE NOT NULL,No_Of_Days_Worked AS DATEDIFF(DD, DOJ, CURRENT_TIMESTAMP));
INSERT Employee_computedcol(EmpName, DOJ)VALUES('Test', '2012-10-01');
select * from Employee_computedcol
Value of No_Of_Days_Worked will be 7

Change the date and time settings of your computer and extend it to 2 more days(if the sql server is in your local machine).
No_Of_Days_Worked will be 9

No comments:

Post a Comment