Sunday, September 5, 2010

CDC (Change Data Capture)



OVERVIEW

CDC is one of the new data tracking and capturing features of SQL Server 2008. It only tracks changes in user-created tables. Because captured data is then stored in relational tables, it can be easily accessed and retrieved subsequently, using regular T-SQL.


PRE-REQUISITE
  • Works only in Enterprise, Developer and Evaluation Edition
  • SQL Agent Service should be up & running
PRE-CONDITION
  • There should not be any schema with a name "cdc"
  • There should not be any column in a table called __$start_lsn, __$end_lsn, __$seqval, __$operation, and __$update_mask

BEST PRACTICE
  • all cdc changes should be tracked in a separate filegroup rather than using Primary
  • configure only required tables and columns

ENABLE CDC ON DATABASE

EXEC sys.sp_cdc_enable_db
Go
SELECT [name], database_id, is_cdc_enabled FROM sys.databases

This will create some columns under "cdc" schema which will be introduced.


ENABLE CDC ON TABLE

EXEC sys.sp_cdc_enable_table
@source_schema = 'dbo', -- Schema Name
@source_name = 'CDCCheck' , -- Table Name
@role_name = NULL,
@captured_column_list = 'a,b,c', -- Comma separate column list, if not given all columns will be considered
@filegroup_name = 'CDCFileGroup'
A new table will be created under CDC schema called "CDC.dbo_CDCCheck_CT". Apart from columns specified above, it will have 5 extra columns
__$Start_lsn - Log Sequence Number
__$end_lsn - Log Sequence Number
__$sequal
__$operation
  • 1 - Insert
  • 2 - Delete
  • 3 - Before Update
  • 4 - After update
__$update_mask
  • if the value is 0x12 means 0b10010 in binary means 2nd and 5th column has been updated
  • if the value is 0x1F means 0b11111 in binary means all 5 columns have been updated

DISABLE CDC ON TABLE
EXECUTE sys.sp_cdc_disable_table
@source_schema = N'HumanResources',
@source_name = N'Shift'


ADVANTAGES OF CDC
  • CDC talks with transaction log, pulls data from there and put them in cdc table. So it gives best performance in comparison with trigger approach
  • Low development cost, easy maintenance, clean approach of tracking audit.

LIMITATION/PROBLEM WITH CDC



  • TRUNCATE won't be allowed if CDC is enabled on table

  • If a new column gets added or existing column gets removed, it does not reflect CDC table. Alternate solution is, cdc should be disabled and enabled.

  • NVARCHAR(MAX), VARBINARY(MAX) columns will be part of each update operation even though their value is untouched. Ex. In a table, there are 4 columns. Out of this one column in NVARCHAR(MAX). Assume that 1 int column value has been changed but NVARCHAR(MAX) is untouched, still in CDC table, it will be tracked as the previous value was NULL and new value is existing value.



Friday, September 3, 2010

SQL CLR

OVERVIEW

SQL CLR refers to the use of CLR code within SQL to make SQL more extensible and make things available which are not possible by simple T-SQL code.

ALLOW SQL INSTANCE TO RUN CLR CODE

EXEC sp_configure 'clr enabled',1
RECONFIGURE


CREATING PROJECT
  • Open Microsoft Visual Studio >> Click New Project >> Select Visual C# >> Database >> SQL Server Project
  • Connect Database
  • Right click on Solution Explorer >> Click on Add >> Stored Procedure
  • Add new stored procedure template
  • Now where it suggest to //Put your code here. Replace it with code displayed in the image. Once the code is complete do following two steps.
  • Click on menu bar >> Build >> Build ProjectName
  • Click on menu bar >> Build >> Deploy ProjectName
SAMPLE CODE

Check whether given string is proper email or not







public static void StoredProcedure1(SqlString email)
    {
        using (SqlConnection conn = new SqlConnection("context connection=true"))
        {
            SqlBoolean isValid = new SqlBoolean();

            isValid = Regex.IsMatch(email.Value, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");

            SqlContext.Pipe.Send(isValid.ToString());
        }
    }




fetch data from particular table
                SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = @"SELECT * FROM IdentityCheck";
            cmd.Parameters.AddWithValue("@email",email);
            conn.Open();

            SqlContext.Pipe.ExecuteAndSend(cmd);

LOAD ASSEMBLY

You can either deploy through VS or you can use following command.
create assembly demo from '<<SoAndSo>>\SqlClassLibrary.dll'

You can check in system table.



select * from sys.assemblies




USING SQL CLR IN DATABASE CODE


EXEC StoredProcedure1 '##abc@gmail.co.in'


OBJECTS CAN BE CREATED USING SQL CLR
  • Stored Procedure
  • Trigger
  • User defined Type
  • User defined Aggregate
  • Scalar Function
  • Table valued Function

Wednesday, September 1, 2010

New features of SQL Server 2005/2008

2005

  • Exception Handling using TRY-CATCH 
  • CTE (Common Table Expression)
  • PIVOT
  • CLR
  • New functions (ROW_NUMBER, RANK, DENSE_RANK )
  • New operands (INTERSECT, EXCEPT)
  • New clause (OUTPUT, TABLESTAMP)
  • New DataType (XML)
  • Data Tuning Advisor

2008

Tuesday, August 10, 2010

System Objects

SYSTEM VARIABLES


Variable
Description
@@ERROR
Contains error number (defined by SQL server) for previous statement. If no error then returns 0
@@FETCH_STATUS
0 à fetch from last statement was successful
-1 à last statement got failed
-2 àfetch was missing
Generally being used in cursor
@@TRANCOUNT
Total number of open transactions
@@ROWCOUNT
Total number of rows affected in last statement. Will work with INSERT, UPDATE, DELETE, SELECT. Won’t work with TRUNCATE
@@IDENTITY
returns the last identity value generated for a specific table in any session and any scope
@@VERSION
Gives SQL Server version


SYSTEM TABLES

MAPPING SYSTEM TABLES

Table
Description
sys.sysdatabases
/ sys.databases
Different info about all the databases available
sys.syslanguages
Different languages and their info (total 32 languages)
sys.sysmessages
/ sys.messages
Contains all SQL server error messages (in all 11 languages) with severity
Sys.syslogins
Contains all logins available in sql server
Sys.sysobjects / sys.objects
Contains all objects created in particular database
XTYPE column will differentiate those objects
U à Table
P à Procedure
V à View
TR à Trigger
FN à Scalar function
TF / IF à Table function
PC à SQL CLR Stored Procedure
PK à Primary Key
F à Foreign Key
C à Check constraint
D à Default constraint
UQ à Unique constraint
Sys.systypes
Contains all SQL server defined types + user defined types. “length” column will tell how many number of bytes it is getting stored.
Nvarchar(250), it will show as 500.
Varchar(250), it will show as 250
Nvarchar(max), it will show as -1
Sys.tables
Contains all the tables within a particular db
Sys.columns
Contains all the columns of all the tables
Sys.procedures
Contains all the procedures
Sys.database_files
Contains all the files
Sys.filegroups
Contains all the file groups
Sys.indexes
Contains all the indexes for each table.
Indid is very important column
  • When 0 means no index available
  • When 1 means clustered index available
  • When 2 means non-clustered index
For each table, there will be only 1 row for indid = 0/1
Sys.index_columns
Contains participant columns for each index
Sys.sql_modules
Contains complete definition of each SP/Function/Trigger

msdb DATABSE TABLES 




Table
Description
backupset
Contains backup details of each backup of all databases
Backupmedafamily
Contains physical path of backup
Backupfile

Sysjobs
Contains all the jobs
Sysjobsteps
Contains all steps for all jobs
Sysjobschedules
Contains job schedule for all jobs
Sysjobhistory
Maintains job execution history at step level.
Run_status (0: failed, 1: success)
Sysjobactivity
Maintains execution history at job level (start time, end time, final status, last execution step id, etc.)



MAPPING SYSTEM TABLES (msdb database)


SYSTEM FUNCTION




DATE FUNCTIONS
GETDATE()
Gives current date time (server’s timezone)
GETUTCDATE()
Gives current date time (GMT + 0 Timezone)
ISDATE('Value')
Returns bool value whether given value is proper date or not
DATEADD(MM,10,GETDATE())
Adds 10 months into current date
DATEPART(YYYY, GETDATE())
Gives only year
DATEDIFF(dd,'2009-01-01','2010-01-01')
Difference of 2 days
DATENAME (MM, GETDATE())
Name of the month
SELECT DATENAME(DW, DATEADD(DD, 1-DAY(GETDATE()), GETDATE()))
First day of the current month
CONVERT(VARCHAR,GETDATE(),XX)
various formats of showing date. XX varies from 100 to 114
                                                                             STRING FUNCTIONS
SPACE(5)
Adds space 5 times
LTRIM()
Trims from left
RTRIM()
Trims from right
REPLACE('India','I','A')
Replaces “I” with “A” in a string “India” à
OUTPUT : AndAa
CHARINDEX('i','India',1)
Gives position of “I” in a string “India” starting from 1st character à OUTPUT : 1
If CHARINDEX('i','India',2)then  OUTPUT : 4
SUBSTRING('Nisarg',2,3)
Gives 3 characters from 2nd position in a given string.
à OUTPUT : isa
REPLICATE('blah',3)
Repeats given string 3 times
à OUTPUT : blahblahblah
RIGHT('India',2)
Gives 2 characters from right side
à OUTPUT : ia
LEFT('India',2)
Gives 2 characters from left side
à OUTPUT : In
LEN('Value')
Gives total number of characters available in given string (after right trimming)
UPPER('inDIA')
Converts all the characters into upper case
LOWER('inDIA')
Converts all the characters into lower case
REVERSE('INDIA')
Reverses the string. à OUTPUT : AIDNI
STUFF('hindustan',3,4,'STUFF')
Replaces 4 characters from 3rd position with given string à OUTPUT : hiSTUFFtan
MATHEMATICAL FUNCTIONS
AVG, SUM, MIN, MAX, COUNT

ISNUMERIC
Checks whether given value is numeric or not. Gives Boolean reult
METADATA FUNCTIONS
DB_ID()
Gives ID of a current database
DB_NAME()
Gives name of current database
OBJECT_NAME(389576426)
Gives name of the objects of given ID
OBJECT_ID('dbo.IndexCheck')
Gives ID from sysobjects table of a given object
SCHEMA_ID('dbo')
Gives ID of a given schema
SCHEMA_NAME(1)
Gives name of a schema with given ID
OTHER FUNCTIONS
ISNULL(ColumnName,'Value')
Replaces NULL value of a given column with passed string
CONVERT(DataType,'Value')
Converts particular value into a given datatype if compatible
SCOPE_IDENTITY()
returns the last identity value generated for any table in the current session and the current scope
IDENT_CURRENT('TableName')
returns the last identity value generated for a specific table in any session and any scope
NEWID()
Gives unique GUID
COALESCE(Column1, Column2, ..., ColumnN)
Gives first Non-NULL value from the list. If all are NULL, SQL server will throw an error
ERROR_NUMBER()
If written in CATCH block then gives error number of an error which caused to execute CATCH block

Outside CATCH block then NULL
ERROR_MESSAGE()
If written in CATCH block then gives error message of an error which caused to execute CATCH block

Outside CATCH block then NULL
ERROR_PROCEDURE()
If written in CATCH block then gives name of SP/Trigger from where error occurred

Outside CATCH block then NULL

If error not from SP/Trigger then NULL
ERROR_LINE()
If written in CATCH block then gives line number from SP/Trigger from where error occurred

Outside CATCH block then NULL

If error not from SP/Trigger then NULL
ERROR_SEVERITY()
If written in CATCH block then gives error serverity of an error which caused to execute CATCH block

Outside CATCH block then NULL