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

Wednesday, October 3, 2012

VARCHAR - when n is not specicfied (where n is the string length)

1. Varchar in Declare
----------------------------------------------------

When Varchar is used to declare a variable and the length is not specified, default  value is 1

For Example

declare @a varchar, --length of varchar is not specied
 @x varchar(5) --length of varchar is 5

set @a = 'xyz'set @x = 'xyz'
select len(@a) as len_not_specified, len(@x) as len_specified 

len_not_specified    len_specified 
--------------------       ------------------
1                     3


2. Varchar in CAST/CONVERT
--------------------------------------------------------------------
When Varchar is used in CAST or CONVERT and the length is not specified, default  value is 30

For Example:

select
len(replicate('a', 40)) as 'LEN_REPLICATE',
LEN(CONVERT(VARCHAR,replicate('a', 40))) AS 'Converted', --length of the varchar is not specified
LEN(CAST(replicate('a', 40) AS VARCHAR)) AS 'Cast' --length of the varchar is not specified


LEN_REPLICATE
     Converted    Cast
-------------     ---------    ----

40                30           30