Thursday, July 15, 2010

Column

COLUMN PROPERTIES

Column Property
Description
NOT NULL
Wont't allow NULL.
Default is NULL; can be changed by
 
ALTER DATABASE <
> SET ANSI_NULL_DEFAULT OFF -- Default NOT NULL
ALTER DATABASE <
> SET ANSI_NULL_DEFAULT ON -- Default NULL

SET ANSI_NULLS ON
 -- can not be compared with ColName = NULL (default)
SET ANSI_NULLS OFF -- can be compared with ColName = NULL (Avaible in that session only)
IDENTITY
For autoincremental value.
Can have only one IDENTITY column per table
SET IDENTITY_INSERT 
ON -- To insert desired value
SET IDENTITY_INSERT 
OFF -- will take value automatically

DBCC CHECKIDENT (table_Name, RESEED, value) -- to set the next desired valu
NOT FOR REPLICATION
Can be applied on IDENTITY Column.
By specifiying this, SQL Server won't reseed the value when replication happens
SPARSE
applicable on nullable columns
Generally NULL occupies some space. When we specifiy SPARSE, null record won't occupy any space; however non-nullable records will occupy 4 bytes in addition to actual storage.
Can be used only when we have high amount of nullable records.
Cannot be applied on IDENTITY, ROWGUID, GEOMETRY, GEOGRAPHY, HIERARCHYID, TIMESTAMP, IMAGE, TEXT, NTEXT, VARBINARY(MAX) WITH FILESTREAM, Computed column, userdefined data type
ROWGUIDCOL
Can be used only with UNIQUEIDENTIFIER datatype.
Only 1 per table
FILESTREAM
Can be applied on VARBINARY(MAX) column.
For that table should have ROWGUID column
Stores the file in Filesystem and maintains the reference in table. This is the best approach to store the Files rather than using Windows File System or complete database approach















COMPUTED COLUMN
CREATE TABLE Comp1 (a int, b int, c as (a+b) persisted)
If persisted specified, then SQL server stores the actual result of the calculation and will be updated automatically whenever changes happen in the columns being used in calculaton.
If persisted not specified, SQL server stores only calculation and while execution, it will calculate the values

Tuesday, July 13, 2010

DataType

DATATYPE



DataType
Storage Size (Bytes)
Values
Comment
Tinyint
1
0 to 255
Smallint
2
-2 x to 2 x - 1
(X: 15)
Int
4
-2 x to 2 x - 1
 (X: 31)
Bigint
8
-2 x to 2 x - 1
 (X: 63)
Numeric
5 to 17
Datetime
8
01/01/1753 to 12/31/9999
Accuracy: 3 miliseconds
smalldatetime
4
01/01/1900 to 06/06/2079
Accuracy: 1 minute
Datetime2
6 to 8
01/01/0001 to 12/31/9999
Accuracy: 100 nanoseconds
datetimeoffset
8 to 10
01/01/0001 to 12/31/9999
Accuracy: 100 nanoseconds
Date
3
01/01/0001 to 12/31/9999
Accuracy: 1 Day
Time
3 to 5
00:00:00.0000000 to
23:59:59.9999999
Accuracy: 100 nanoseconds
Char
As specified
Only english characters are allowed
Text
generally not used now
Varchar
as specified
max 2 GB
Only english characters are allowed
Nchar
As specified
(double the char)
Non-english characters are allowed
Ntext
generally not used now
Nvarchar
as specified
(double the varchar)
max: upto 2 GB
Can store non-english characters
Binary
As specified
Varbinary
Variable As specified
max: upto 2 GB
FILESTREAM can be used with VARBINARY(MAX)
Image
16
generally not used now
Cursor
Hierarchyid
892 bytes
Binary number maintains the
hierarchy
sql_variant
timestamp/
rowversion
nullable : varbinary(8)
non-nullable: binary(8)
Unique Binary number
throught database
uniqueidentifier
16
NEWID function can be used
Xml
max: upto 2 GB
Maximum 128 levels
Geography
max: upto 2 GB
Geometry
max: upto 2 GB

User Defined Data Types:
CREATE TYPE City FROM VARCHAR(255) NOT NULL
CREATE TABLE Info (A INT, B CITY)

Sunday, July 11, 2010

View

OVERVIEW
  •  A virtual entity of DB which looks like a table but does not store the records physically.
  •  It is something like window over a table
  •  Complex query can be converted into view and can be used in FROM clause
  •  A table can be dropped even though view is existing which is using this table. However view created with SCHEMABINDING option won’t allow dropping a table
  •  All DML operations are possible on View but again it has some limitations. 
    • It shouldn't violate any constraint like foreign key, unique, identity, not null, etc.
    • View should point to only 1 table and not multiple tables
    • View should not have GROUP by clause or any arithmetic functions 
  •  Won’t allow SELECT INTO, ORDER BY
  • We can use ORDER BY but it should have TOP operator then only we can use it
  •  Index can be created on view but with following conditions. If we do this, view will start storing the data physically
    • View should be schemabound
    • First we have to create unique clustered index then only we can create other non-clustered indexes
  • Creating index on view is sort of alternate solution of partition.
SYNTAX

  • Basic Syntax
CREATE VIEW vwName
AS
SELECT QUERY


  • With Schemabinding syntax


CREATE VIEW vw
WITH SCHEMABINDING
AS
    SELECT eid, ename , salary, dob
    FROM dbo.Employee
    WHERE Salary > 10000


Friday, July 9, 2010

Cursor

  • Allows row-by-row processing. Control will be with user rather than SQL server
  • Different options can be applied while creating a cursor
o Local/global
o Static/dynamic/fast_forward/ketyset driven
o Forward_only/scroll
  • Generally it should be avoided as it is affecting a performance a big time
  • If another SP is being called within cursor, it will fail. So while loop should be used instead of cursor
  • A general syntax
DECLARE cur CURSOR
FOR SELECT a,b FROM TableName
OPEN cur
FETCH NEXT FROM Cur INTO @a, @b
WHILE @@FETCH_STATUS = 0
BEGIN
-- Your logic
FETCH NEXT FROM Cur INTO @a, @b
END
CLOSE cur
DEALLOCATE cur
  • In some cases, Cursor will be faster than normal join e.g. 
    • when there is some N level of parent-child relationship than rather than joining the same table multiple times, we can use cursor and achieve the results fast
    • When you have to insert millions of record in one table then probably you can start cursor and insert a bunch of records (let's say 25K records) in chunks which will be faster than a single INSERT statement
  • Even if we have to use cursor, it is recommended that we use WHILE LOOP rather than using cursor

Wednesday, July 7, 2010

Trigger

Definition: A special type of SPs which are defined to execute automatically when UPDATE/INSERT/DELETE statement is issued against a table/view
OR some DDL operation happens in database


Special tables
Inside DML trigger, we can use special tables like INSERTED or DELETED.
INSERTED table will contain the new value/record for particular table
DELETED table will contain the old value/record for particular table

Type of Triggers

  • DML Trigger
    • Before Trigger
      • Getting executed before actual operation
      • we can create N number of before triggers per table per action (IUD)
      • Syntax
      • CREATE TRIGGER trg ON TriggerCheck FOR INSERT -- Before
        AS
        BEGIN
              DECLARE @newValue VARCHAR(10)
             
              SELECT @newValue = tname FROM INSERTED
             
              PRINT @newValue
        END
    • After Trigger
      • Getting executed after actual operation
      • we can create N number of before triggers per table per action (IUD)
      • Syntax
      • CREATE TRIGGER trg ON TriggerCheck AFTER INSERT
        AS
        BEGIN
              DECLARE @newValue VARCHAR(10)
             
              SELECT @newValue = tname FROM INSERTED
             
              PRINT @newValue
        END
    • Instead of Trigger
      • Getting executed instead of actual operation
      • We can create only 1 instead of trigger per table per action (IUD)
      • Syntax
      • CREATE TRIGGER trg ON TriggerCheck INSTEAD OF INSERT
        AS
        BEGIN
              PRINT 'Not allowed'
        END
  • DDL Trigger
    • Introduced in 2005
    • we can track DDL activities like CREATE, DROP, ALTER table/view/sp at database level or CREATE, DROP database/login at server level
    • useful in following areas
      • Auditing
      • Maintaining coding standards for table/sp/function name
      • For alert whenever some DDL activities happen at database level
    • EVENTDATA is a special function which can be used inside trigger and returns XML data which can be further used for tracking
    • let's say we want to track DDL activities within database then first we can create one customized table like this
    • CREATE TABLE tblDDLEventLog
      (
          ID int IDENTITY(1,1) NOT NULL,
          EventTime datetime,
          EventType varchar(15),
          ServerName varchar(25),
          DatabaseName varchar(25),
          ObjectType varchar(25),
          ObjectName varchar(25),
          UserName varchar(15),
          CommandText varchar(max)
      )
    • Now, create trigger to capture create table events
    • CREATE TRIGGER ddltrg_CREATE_TABLE_LOG ON DATABASE -- Create Database DDL Trigger
      FOR CREATE_TABLE -- Trigger will raise when creating a Table
      AS
          DECLARE @xmlEventData XML
          -- Capture the event data that is created
          SET @xmlEventData = eventdata()
          -- Insert information to a EventLog table
          INSERT INTO tblDDLEventLog
          (
              EventTime,
              EventType,
              ServerName,
              DatabaseName,
              ObjectType,
              ObjectName,
              UserName,
              CommandText
          )
          SELECT  REPLACE(CONVERT(VARCHAR(50), @xmlEventData.query('data(/EVENT_INSTANCE/PostTime)')),'T', ' '),
                  CONVERT(VARCHAR(15), @xmlEventData.query('data(/EVENT_INSTANCE/EventType)')),
                  CONVERT(VARCHAR(25), @xmlEventData.query('data(/EVENT_INSTANCE/ServerName)')),
                  CONVERT(VARCHAR(25), @xmlEventData.query('data(/EVENT_INSTANCE/DatabaseName)')),
                  CONVERT(VARCHAR(25), @xmlEventData.query('data(/EVENT_INSTANCE/ObjectType)')),
                  CONVERT(VARCHAR(25), @xmlEventData.query('data(/EVENT_INSTANCE/ObjectName)')),
                  CONVERT(VARCHAR(15), @xmlEventData.query('data(/EVENT_INSTANCE/UserName)')),
                  CONVERT(VARCHAR(MAX), @xmlEventData.query('data(/EVENT_INSTANCE/TSQLCommand/CommandText)'))
      GO
    • Now create some table and check the entries in tblDDLEventLog table.


Something Extra
  • Debugging of DML Trigger is difficult
  • Generally DML triggers should be avoided and rather the same logic can be implemented at SP level
  • Auditing of data can be handled by CDC
  • If multiple BEFORE or AFTER triggers are available for single DML operation, then order will be same as it got created. However, sp_settriggerorder can be used to set the first and last order of trigger execution


Monday, July 5, 2010

Function

Definition: a bunch of SQL Statements which can be stored under 1 name.
Type of Function
      · Scalar Function
o Returns a single value
CREATE FUNCTION Fun1 (@a int)
RETURNS int
AS
BEGIN
DECLARE @B int
SET @B = @A
RETURN(@b)
END
      · Table valued Function
o Returns a table (only 1)
CREATE FUNCTION Fun2 (@a int)
RETURNS @temp table (B int)
AS
BEGIN
INSERT INTO @temp (B) VALUES (@A)
RETURN
END
      · Aggregate Function
      · System Function
o Mathematical functions, Date functions, etc…

Difference between SP and Function
  • A scalar valued function can be used in SELECT and WHERE clause and a table-valued function can be used in FROM clause. SP cannot be used anywhere
  • Function won’t except OUTPUT pram, SP does
  • You cannot call an SP, cannot create #TEMP table, cannot use DML and DDL statements inside function. SP will allow.
  • Function can be used as User Defined DataType, SP cannot
  • You cannot return text, image, timestamp from a function
  • Default Param