You are on page 1of 213

Swap the values of two columns in SQL Server

Do you have fun with SQL Server?. Let's start fun with SQL Server. Suppose you want to swap the values of two columns of a table in SQL Server, how could you achieve this tricky task?. Actually, it is simple and so funny. Suppose you have a Customer table in the database with the following data and you want to interchange the values of columns Name and Address then how do you do?
SELECT * FROM CUSTOMER

Don't worry, to do this task, you need to just write a simple update query for Customer table like as :
UPDATE Customer SET Name=Address , Address=Name

Now After query execution you will find the the values of columns Name and Address have been interchanged, that's so cool.
SELECT * FROM CUSTOMER

Enable Intellisense in SQL Server 2005, 2008

By default, SQL Server 2000, 2005, 2008 and 2008R2 doesn't provide intellisense like Visual Studio. While writing T-SQL statements, we need to recall the database table structure (including columns, their data types, size) and other database objects structure like stored procedure, view and functions again and again. Sometimes it becomes tedious task. Don't worry, we have some tools for enabling intellisense in SQL Server like as SQL Complete, SQL Developer Bundle that are free to use and also have their standard versions for advanced features.

SQL Complete
This is a very use ful tools and provide good intellisense help in SQL Server. First download its free or standard version and installed it. After installing you will see a new menu option "SQL Complete" in SQL Server menu as shown in fig.

Now, whenever you will wrie your T-SQL query, it will provides the intellisense help like Visual Studio like as :

SQL Developer Bundle


This is also very use ful tools and provide good intellisense help in SQL Server. First download its free or standard version and installed it. After installing you will see a new menu option "SQL Source Control and SQL Search" in SQL Server menu as shown in fig.

Now, whenever you will wrie your T-SQL query, it will provides the intellisense help like Visual Studio like as :

Drop all tables, stored procedure, views and triggers


Sometimes, there is a case, when we need to remove all tables, stored procedure, views and triggers completely from the database. If you have around 100 tables, stored procedure and views in your database, to remove these, completely from database became a tedious task. In this article, I would like to share the script by which you can remove tables, stored procedure, views and triggers completely from database.

Remove all Tables


-- drop all user defined tables EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

Remove all User-defined Stored Procedures


-- drop all user defined stored procedures Declare @procName varchar(500) Declare cur Cursor For Select [name] From sys.objects where type = 'p' Open cur Fetch Next From cur Into @procName While @@fetch_status = 0 Begin Exec('drop procedure ' + @procName) Fetch Next From cur Into @procName End Close cur Deallocate cur

Remove all Views


-- drop all user defined views Declare @viewName varchar(500) Declare cur Cursor For Select [name] From sys.objects where type = 'v' Open cur Fetch Next From cur Into @viewName While @@fetch_status = 0 Begin Exec('drop view ' + @viewName) Fetch Next From cur Into @viewName End Close cur Deallocate cur

Remove all Triggers


-- drop all user defined triggers Declare @trgName varchar(500) Declare cur Cursor For Select [name] From sys.objects where type = 'tr' Open cur Fetch Next From cur Into @trgName While @@fetch_status = 0 Begin Exec('drop trigger ' + @trgName)

Fetch Next From cur Into @trgName End Close cur Deallocate cur

Difference between Primary Key and Unique Key


In SQL Server, we have two keys which distinctively or uniquely identify a record in the database. Both the keys seems identical, but actually both are different in features and behaviours. In this article, I would like to share the key difference between primary key and unique key. For more help about keys in SQL Server refer the article Different Types of SQL Keys.
Difference between Primary Key & Unique Key Primary Key Unique Key Primary Key can't accept null values. Unique key can accept only one null value. By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. By default, Unique key is non-clustered index. We can have only one Primary key in a table. We can have more than one unique key in a table. Primary key can be made foreign key into another table. Unique key can't be made foreign key into another table.

Define Primary key and Unique key


1. 2. 3. 4. 5. 6. 7. CREATE TABLE Employee ( EmpID int PRIMARY KEY, --define primary key Name varchar (50) NOT NULL, MobileNo int UNIQUE, --define unique key Salary int NULL )

Difference between Primary Key and Foreign Key


In SQL Server, there are two keys - primary key and foreign key which seems identical, but actually both are different in features and behaviours. In this article, I would like to share the key

difference between primary key and foreign key. For more help about keys in SQL Server refer the article Different Types of SQL Keys.
Difference between Primary Key & Foreign Key Primary Key Foreign Key Primary key uniquely identify a record in the table. Foreign key is a field in the table that is primary key in another table. Primary Key can't accept null values. Foreign key can accept multiple null value. By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. While Foreign key is non-clustered index. We can have only one Primary key in a table. We can have more than one foreign key in a table.

Define Primary key and Foreign key


1. --Create Parent Table 2. CREATE TABLE Department 3. ( 4. DeptID int PRIMARY KEY, --define primary key 5. Name varchar (50) NOT NULL, 6. Address varchar(100) NULL 7. ) 8. GO 9. --Create Child Table 10. CREATE TABLE Employee 11. ( 12. EmpID int PRIMARY KEY, --define primary key 13. Name varchar (50) NOT NULL, 14. Salary int NULL, 15. --define foreign key 16. DeptID int FOREIGN KEY REFERENCES Department(DeptID) 17. )

Magic table or Virtual table in SQL Server


Basically, magic table is the terminology used for virtual table in SQL Server since there is no magic in SQL Server. There are Inserted and Deleted virtual tables in SQL Server. These tables are automatically created and managed by SQL Server internally to hold recently inserted, deleted and updated values during DML operations (Insert,Update,Delete) on a database table.

Use of virtual tables


Basically, virtual tables are used by triggers for the following purpose:

1. To test data manipulation errors and take suitable actions based on the errors. 2. To find the difference between the state of a table before and after the data modification and take actions based on that difference.

Inserted Virtual Table


The Inserted table holds the recently inserted or updated values means new data values. Hence newly added and updated records are inserted into the Inserted table. Suppose we have Employee table as shown in fig. Now We need to create two triggers to see data with in virtual tables Inserted and Deleted.

1. 2. 3. 4. 5. 6. 7. 8.

CREATE TRIGGER trg_Emp_Ins ON Employee FOR INSERT AS begin SELECT * FROM INSERTED -- show data in Inserted virtual table SELECT * FROM DELETED -- show data in Deleted virtual table end

In the bwlow
1. --Now insert a new record in Employee table to see data with in Inserted virtual tables 2. INSERT INTO Employee(EmpID, Name, Salary) VALUES(3,'Avin',23000) 3. SELECT * FROM Employee

Deleted Virtual Table


The Deleted table holds the recently deleted or updated values means old data values. Hence old updated and deleted records are inserted into the Deleted table.
1. 2. 3. 4. 5. 6. 7. 8. CREATE TRIGGER trg_Emp_Upd ON Employee FOR UPDATE AS begin SELECT * FROM INSERTED -- show data in INSERTED virtual table SELECT * FROM DELETED -- show data in DELETED virtual table end

1.

--Now update the record in Employee table to see data with in Inserted and Deleted Virtual tables 2. Update Employee set Salary=43000 where EmpID=3 3. SELECT * FROM Employee

We could not create the virtual tables or modify the data with in the virtual tables. When we use the OUTPUT clause in SQL Server 2005, 2008 & 2012, then virtual tables are automatically created and managed by SQL Server.

Difference between Stored Procedure and Function in SQL Server


Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called. But Function is compiled

and executed every time it is called. For more about stored procedure and function refer the articles Different types of Stored Procedure and Different types of Function.
Basic Difference

1. Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values). 2. Functions can have only input parameters for it whereas Procedures can have input/output parameters . 3. Function takes one input parameter it is mandatory but Stored Procedure may take o to n input parameters.. 4. Functions can be called from Procedure whereas Procedures cannot be called from Function.
Advance Difference

1. Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it. 2. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement. 3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be. 4. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables. 5. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations. 6. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function. 7. We can go for Transaction Management in Procedure whereas we can't go in Function.

Get field name, data type and size of database table


One student of me asked "how can we get fields name of a table with theirs type and size ?". In this article I am going to expose, how can we achieve this in SQL Server.

Query to get field name with datatype and size


SELECT column_name as 'Column Name', data_type as 'Data Type', character_maximum_length as 'Max Length' FROM information_schema.columns WHERE table_name = 'tblUsers'

Get nth highest and lowest salary of an employee


One student of me asked "how can we get nth highest and lowest salary on an employee ?". In this article I am going to expose, how can we achieve this in SQL Server. Suppose we have employee name and salary as shown in below fig.

Query to get nth(3rd) Highest Salary


1. Select TOP 1 Salary as '3rd Highest Salary' 2. from (SELECT DISTINCT TOP 3 Salary from Employee ORDER BY Salary DESC)

3. a ORDER BY Salary ASC

Query to get nth(3rd) Lowest Salary


1. Select TOP 1 Salary as '3rd Lowest Salary' 2. from (SELECT DISTINCT TOP 3 Salary from Employee ORDER BY Salary ASC) 3. a ORDER BY Salary DESC

Tips to improve SQL Server database design and performance


Best performance is the main concern to develop a successful application. Like a coin database is the tail side (back-end) of an application. A good database design provides best performance during data manipulation which results into the best performance of an application. During database designing and data manipulation we should consider the following key points:

Choose Appropriate Data Type


Choose appropriate SQL Data Type to store your data since it also helps in to improve the query performance. Example: To store strings use varchar in place of text data type since varchar performs better than text. Use text data type, whenever you required storing of large text data (more than 8000 characters). Up to 8000 characters data you can store in varchar.

Avoid nchar and nvarchar


Does practice to avoid nchar and nvarchar data type since both the data types takes just double memory as char and varchar. Use nchar and nvarchar when you required to store Unicode (16-bit characters) data like as Hindi, Chinese characters etc.

Avoid NULL in fixed-length field

Does practice to avoid the insertion of NULL values in the fixed-length (char) field. Since, NULL takes the same space as desired input value for that field. In case of requirement of NULL, use variable-length (varchar) field that takes less space for NULL.

Avoid * in SELECT statement


Does practice to avoid * in Select statement since SQL Server converts the * to columns name before query execution. One more thing, instead of querying all columns by using * in select statement, give the name of columns which you required.
1. -- Avoid 2. SELECT * FROM tblName 3. --Best practice 4. SELECT col1,col2,col3 FROM tblName

Use EXISTS instead of IN

Does practice to use EXISTS to check existence instead of IN since EXISTS is faster than IN.
5. -- Avoid 6. SELECT Name,Price FROM tblProduct 7. where ProductID IN (Select distinct ProductID from tblOrder) 8. --Best practice 9. SELECT Name,Price FROM tblProduct 10. where ProductID EXISTS (Select distinct ProductID from tblOrder)

Avoid Having Clause

Does practice to avoid Having Clause since it acts as filter over selected rows. Having clause is required if you further wish to filter the result of an aggregations. Don't use HAVING clause for any other purpose.

Create Clustered and Non-Clustered Indexes


Does practice to create clustered and non clustered index since indexes helps in to access data fastly. But be careful, more indexes on a tables will slow the INSERT,UPDATE,DELETE operations. Hence try to keep small no of indexes on a table.

Keep clustered index small


Does practice to keep clustered index as much as possible since the fields used in clustered index may also used in nonclustered index and data in the database is also stored in the order of clustered index. Hence a large clustered index on a table with a large number of rows increase the size significantly. Please refer the article Effective Clustered Indexes

Avoid Cursors

Does practice to avoid cursor since cursor are very slow in performance. Always try to use SQL Server cursor alternative. Please refer the article Cursor Alternative.

Use Table variable inplace of Temp table


Does practice to use Table varible in place of Temp table since Temp table resides in the TempDb database. Hence use of Temp tables required interaction with TempDb database that is a little bit time taking task.

Use UNION ALL inplace of UNION


Does practice to use UNION ALL in place of UNION since it is faster than UNION as it doesn't sort the result set for distinguished values.

Use Schema name before SQL objects name


Does practice to use schema name before SQL object name followed by "." since it helps the SQL Server for finding that object in a specific schema. As a result performance is best.
11. 12. 13. 14. --Here dbo is schema name SELECT col1,col2 from dbo.tblName -- Avoid SELECT col1,col2 from tblName

Keep Transaction small

Does practice to keep transaction as small as possible since transaction lock the processing tables data during its life. Some times long transaction may results into deadlocks. Please refer the article SQL Server Transactions Management

SET NOCOUNT ON
Does practice to set NOCOUNT ON since SQL Server returns number of rows effected by SELECT,INSERT,UPDATE and DELETE statement. We can stop this by setting NOCOUNT ON like as:
15. 16. 17. 18. 19. 20. 21. CREATE PROCEDURE dbo.MyTestProc AS SET NOCOUNT ON BEGIN . . END

Use TRY-Catch
Does practice to use TRY-CATCH for handling errors in T-SQL statements. Sometimes an error in a running transaction may cause deadlock if you have no handle error by using TRY-CATCH. Please refer the article Exception Handling by TRYCATCH

Use Stored Procedure for frequently used data and more complex queries
Does practice to create stored procedure for quaery that is required to access data frequently. We also created stored procedure for resolving more complex task.

Avoid prefix "sp_" with user defined stored procedure name


Does practice to avoid prefix "sp_" with user defined stored procedure name since system defined stored procedure name starts with prefix "sp_". Hence SQL server first search the user defined procedure in the master database and after that in the current session database. This is time consuming and may give unexcepted result if system defined stored procedure have the same name as your defined procedure.

Remove duplicate records from a table in SQL Server


Sometimes we required to remove duplicate records from a table although table has a UniqueID Column with identity. In this article, I would like to share a best way to delete duplicate records from a table in SQL Server. Suppose we have below Employee table in SQL Server.
1. 2. 3. 4. 5. 6. 7. CREATE TABLE dbo.Employee ( EmpID int IDENTITY(1,1) NOT NULL, Name varchar(55) NULL, Salary decimal(10, 2) NULL, Designation varchar(20) NULL )

The data in this table is as shown below:

Remove Duplicate Records by using ROW_NUMBER()


1. WITH TempEmp (Name,duplicateRecCount)

2. AS 3. ( 4. SELECT Name,ROW_NUMBER() OVER(PARTITION by Name, Salary ORDER BY Name) 5. AS duplicateRecCount 6. FROM dbo.Employee 7. ) 8. --Now Delete Duplicate Records 9. DELETE FROM TempEmp 10. WHERE duplicateRecCount > 1 1. --See affected table 2. Select * from Employee

For more help about ROW_NUMBER(), please follow the MSDN link.

Create a comma separated list from column using select statement


Sometimes we required to generate a comma separated list of columns values like a list of EmailIDs to send mail. In SQL Server, we can make a comma separated list by using COALESCE as shown in below.

Use of COALESCE to create comma separated list


Suppose we have following data in Employee table and we need to make a semicolon separated list of EmailIDs to send mail, then we can use COALESCE as shown in below fig.

Here I am creating a semicolon(;) separated list. You can use comma(,) in place of semicolon to make comma separated list.

For SQL Server database mail setup and configuration and more over how to send mail from SQL Server database you can refer this article.

Database Normalization Basics


Normalization or data normalization is a process to organize the data into tabular format (database tables). A good database design includes the normalization, without normalization a database system may slow, inefficient and might not produce the expected result. Normalization reduces the data redundancy and inconsistent data dependency.

Normal Forms
We organize the data into database tables by using normal forms rules or conditions. Normal forms help us to make a good database design. Generally we organize the data up to third normal form. We rarely use the fourth and fifth normal form. To understand normal forms consider the folowing unnormalized database table. Now we will normalize the data of below table using normal forms.

First Normal Form (1NF)


A database table is said to be in 1NF if it contains no repeating fields/columns. The process of converting the UNF table into 1NF is as follows: 1. Separate the repeating fields into new database tables along with the key from unnormalized database table. 2. The primary key of new database tables may be a composite key 1NF of above UNF table is as follows:

Second Normal Form (2NF)


A database table is said to be in 2NF if it is in 1NF and contains only those fields/columns that are functionally dependent(means the value of field is determined by the value of another field(s)) on the primary key. In 2NF we remove the partial dependencies of any non-key field.
The process of converting the database table into 2NF is as follows:

3. Remove the partial dependencies(A type of functional dependency where a field is only functionally dependent on the part of primary key) of any non-key field. 4. If field B depends on field A and vice versa. Also for a given value of B, we have only one possible value of A and vice versa, Then we put the field B in to new database table where B will be primary key and also marked as foreign key in parent table. 2NF of above 1NF tables is as follows:

Third Normal Form (3NF)


A database table is said to be in 3NF if it is in 2NF and all non keys fields should be dependent on primary key or We can also said a table to be in 3NF if it is in 2NF and no fields of the table is transitively functionally dependent on the primary key.The process of converting the table into 3NF is as follows: 5. Remove the transitive dependecies(A type of functional dependency where a field is functionally dependent on the Field that is not the primary key.Hence its value is determined, indirectly by the primary key )

6. Make separate table for transitive dependent Field. 3NF of above 2NF tables is as follows:

Boyce Code Normal Form (BCNF)


A database table is said to be in BCNF if it is in 3NF and contains each and every determinant as a candidate key.The process of converting the table into BCNF is as follows: 7. Remove the non trival functional dependency. 8. Make separate table for the determinants. BCNF of below table is as follows:

Fourth Normal Form (4NF)


A database table is said to be in 4NF if it is in BCNF and primary key has one-to-one relationship to all non keys fields or We can also said a table to be in 4NF if it is in BCNF and contains no multi-valued dependencies.The process of converting the table into 4NF is as follows: 9. Remove the multivalued dependency. 10. Make separate table for multivalued Fields. 4NF of below table is as follows:

Fifth Normal Form (5NF)


A database table is said to be in 5NF if it is in 4NF and contains no redundant values or We can also said a table to be in 5NF if it is in 4NF and contains no join dependencies.The process of converting the table into 5NF is as follows: 11. Remove the join dependency. 12. Break the database table into smaller and smaller tables to remove all data redundancy. 5NF of below table is as follows:

SQL Server Cursor Alternatives


As we know, the cursors are required when we need to update records in a database table in singleton fashion means row by row. A Cursor also impacts the performance of the SQL Server since it uses the SQL Server instances memory, reduce concurrency, decrease network bandwidth and lock resources. You should avoid the use of cursor. In this article, I am explaining how you can use cursor alternatives like as WHILE loop, Temporary tables and Table variables. We should use cursor in that case when there is no option except cursor.

Example of Cursor Alternative


Suppose we have table "ProductSales" that stores the information about each product sales. Now we want to calculate the Total Sales Quantity and Amount of each and every product. We can solve this problem by following three methods.
( CREATE TABLE ProductsSales

ID int IDENTITY(1,1) NOT NULL, ProductID int NOT NULL, ProductName varchar(50) NOT NULL, Qty int NOT NULL, Amount decimal(10, 2) NOT NULL ) GO SELECT * FROM ProductsSales --We have the table with below data

Problem solution methods Using Cursor


1. SET NOCOUNT ON 2. DECLARE @ProductID INT 3. DECLARE @ProductName VARCHAR(100) 4. DECLARE @TotalQty INT 5. DECLARE @Total INT 6. DECLARE @TProductSales TABLE 7. ( 8. SNo INT IDENTITY(1,1), 9. ProductID INT, 10. ProductName VARCHAR(100), 11. TotalQty INT, 12. GrandTotal INT 13. ) --Declare Cursor DECLARE Cur_Product CURSOR 14. FOR SELECT DISTINCT ProductID FROM ProductsSales 15. --Open Cursor 16. OPEN Cur_Product 17. --Fetch Cursor 18. FETCH NEXT FROM Cur_Product INTO @ProductID 19. WHILE @@FETCH_STATUS = 0 20. BEGIN 21. SELECT @ProductName = ProductName FROM ProductsSales WHERE ProductID = @ProductID

22. SELECT @TotalQty = SUM(Qty),@Total = SUM(Amount) FROM ProductsSales WHERE ProductID = @ProductID 23. INSERT INTO @TProductSales(ProductID,ProductName,TotalQty,GrandTotal) VALUES(@ProductID,@ProductName,@TotalQty,@Total) 24. FETCH NEXT FROM Cur_Product INTO @ProductID END 25. --Close and Deallocate Cursor 26. CLOSE Cur_Product 27. DEALLOCATE Cur_Product 28. --See Calculated data SELECT * FROM @TProductSales

Using Table Variable


29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. SET NOCOUNT ON DECLARE @ProductID INT DECLARE @ProductName VARCHAR(100) DECLARE @TotalQty INT DECLARE @Total INT DECLARE @i INT =1 DECLARE @count INT --Declare Table variables for storing data DECLARE @TProduct TABLE ( SNo INT IDENTITY(1,1), ProductID INT ) DECLARE @TProductSales TABLE ( SNo INT IDENTITY(1,1), ProductID INT, ProductName VARCHAR(100), TotalQty INT, GrandTotal INT ) --Insert data to Table variable @Product INSERT INTO @TProduct(ProductID) SELECT DISTINCT ProductID FROM ProductsSales ORDER BY ProductID ASC -- Count number of rows SELECT @count = COUNT(SNo) FROM @TProduct WHILE (@i <= @count) BEGIN SELECT @ProductID = ProductID FROM @TProduct WHERE SNo = @i SELECT @ProductName = ProductName FROM ProductsSales WHERE ProductID = @ProductID 56. SELECT @TotalQty = SUM(Qty),@Total = SUM(Amount) FROM ProductsSales WHERE ProductID = @ProductID 57. INSERT INTO @TProductSales(ProductID,ProductName,TotalQty,GrandTotal) VALUES(@ProductID,@ProductName,@TotalQty,@Total) 58. SELECT @i = @i + 1 59. END 60. --See Calculated data

SELECT * FROM @TProductSales

Using Temporary Table


61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. SET NOCOUNT ON DECLARE @ProductID INT DECLARE @ProductName VARCHAR(100) DECLARE @TotalQty INT DECLARE @Total INT DECLARE @i INT =1 DECLARE @count INT --Create Temporary Tables for storing data CREATE TABLE #TProduct ( SNo INT IDENTITY(1,1), ProductID INT ) CREATE TABLE #TProductSales ( SNo INT IDENTITY(1,1), ProductID INT, ProductName VARCHAR(100), TotalQty INT, GrandTotal INT

) 76. --Insert data to temporary table #Product 77. INSERT INTO #TProduct(ProductID) SELECT DISTINCT ProductID FROM ProductsSales ORDER BY ProductID ASC 78. SELECT @count = COUNT(SNo) FROM #TProduct 79. WHILE (@i <= @count) 80. BEGIN 81. SELECT @ProductID = ProductID FROM #TProduct WHERE SNo = @i 82. SELECT @ProductName = ProductName FROM ProductsSales WHERE ProductID = @ProductID 83. SELECT @TotalQty = SUM(Qty),@Total = SUM(Amount) FROM ProductsSales WHERE ProductID = @ProductID 84. INSERT INTO #TProductSales(ProductID,ProductName,TotalQty,GrandTotal) VALUES(@ProductID,@ProductName,@TotalQty,@Total) 85. SELECT @i = @i + 1 86. END 87. --See Calculated data 88. SELECT * FROM #TProductSales 89. --Now Drop Temporary Tables 90. DROP TABLE #TProduct DROP TABLE #TProductSales

SQL Server Setting Triggers Firing Order


Sometimes we have multiple triggers on the same event(s). In that case we can't predict the firing order of triggers. Sometimes the firing order of trigger(s) is important for us to implement business logic. To solve this issue, In SQL Server we have option to set the firing order of triggers on same event(s).

Syntax for setting trigger firing order


1. sp_settriggerorder @triggername='trg_name', @order='FIRST|LAST|NONE', @stmttype='INSERT|UPDATE|DELETE|CREATE_INDEX,ALTER_INDEX', @namespace='DATABASE|SERVER|NULL'

Simple example for setting trigger firing order


1. CREATE TABLE dbo.TestTable ( 2. ID int NOT NULL, 3. Description varchar(100) 4. ) 5. GO 6. --Now create triggers on above created table at same event INSERT 7. CREATE TRIGGER dbo.trg_i_TriggerOrder1 8. ON dbo.TestTable 9. AFTER INSERT 10. As 11. PRINT 'I will be fired first.' 12. GO 13. CREATE TRIGGER dbo.trg_i_TriggerOrder2 14. ON dbo.TestTable 15. AFTER INSERT 16. AS 17. PRINT 'I will be fired last.' 18. GO 19. CREATE TRIGGER dbo.trg_i_TriggerOrder3 20. ON dbo.TestTable 21. AFTER INSERT 22. AS 23. PRINT 'I won''t be first or last.' 24. GO

Set Triggers Firing Order


1. --Now set triggers firing orders 2. EXEC sp_settriggerorder 'dbo.trg_i_TriggerOrder1', 'First', 'INSERT' 3. EXEC sp_settriggerorder 'dbo.trg_i_TriggerOrder2', 'Last', 'INSERT' 4. --The order of firing the third trigger 'dbo.trg_i_TriggerOrder3' will be between above two 1. --Insert data to see trigger firing order 2. INSERT dbo.TestTable(ID,Description)VALUES (1,'Trigger firing order')

SQL Server Different Types of Cursors


A Cursor allow us to retrieve data from a result set in singleton fashion means row by row. Cursor are required when we need to update records in a database table one row at a time. I have already explained the basic of cursor. A Cursor impacts the performance of the SQL Server since it uses the SQL Server instances' memory, reduce concurrency, decrease network bandwidth and lock resources. Hence it is mandatory to understand the cursor types and its functions so that you can use suitable cursor according to your needs. You should avoid the use of cursor. Basically you should use cursor alternatives like as WHILE loop, sub queries, Temporary tables and Table variables. We should use cursor in that case when there is no option except cursor.

Types of Cursors Static Cursors


A static cursor populates the result set at the time of cursor creation and query result is cached for the lifetime of the cursor. A static cursor can move forward and backward direction. A static cursor is slower and use more memory in comparison to other cursor. Hence you should use it only if scrolling is required and other types of cursors are not suitable. You can't update, delete data using static cursor. It is not sensitive to any changes to the original data source. By default static cursors are scrollable.

Dynamic Cursors
A dynamic cursor allows you to see the data updation, deletion and insertion in the data source while the cursor is open. Hence a dynamic cursor is sensitive to any changes to the data source and supports update, delete operations. By default dynamic cursors are scrollable.

Forward Only Cursors


A forward only cursor is the fastest cursor among the all cursors but it doesn't support backward scrolling. You can update, delete data using Forward Only cursor. It is sensitive to any changes to the original data source. There are three more types of Forward Only Cursors.Forward_Only KEYSET, FORWARD_ONLY STATIC and FAST_FORWARD. A FORWARD_ONLY STATIC Cursor is populated at the time of creation and cached the data to the cursor lifetime. It is not sensitive to any changes to the data source. A FAST_FORWARD Cursor is the fastest cursor and it is not sensitive to any changes to the data source.

Keyset Driven Cursors


A keyset driven cursor is controlled by a set of unique identifiers as the keys in the keyset. The keyset depends on all the rows that qualified the SELECT statement at the time of cursor was opened. A keyset driven cursor is sensitive to any changes to the data source and supports update, delete operations. By default keyset driven cursors are scrollable.

SQL SERVER Examples of Cursors


1. 2. 3. 4. 5. 6. 7. 8. 9. CREATE TABLE Employee ( EmpID int PRIMARY KEY, EmpName varchar (50) NOT NULL, Salary int NOT NULL, Address varchar (200) NOT NULL,

) GO INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida') 10. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi') 11. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun') 12. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida')

13. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon') 14. GO 15. SELECT * FROM Employee

Static Cursor - Example


1. SET NOCOUNT ON 2. DECLARE @Id int 3. DECLARE @name varchar(50) 4. DECLARE @salary int 5. DECLARE cur_emp CURSOR 6. STATIC FOR 7. SELECT EmpID,EmpName,Salary from Employee 8. OPEN cur_emp 9. IF @@CURSOR_ROWS > 0 10. BEGIN 11. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary 12. WHILE @@Fetch_status = 0 13. BEGIN 14. PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+ ', Salary : '+convert(varchar(20),@salary) 15. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary 16. END 17. END 18. CLOSE cur_emp 19. DEALLOCATE cur_emp 20. SET NOCOUNT OFF

Dynamic Cursor - Example


1. --Dynamic Cursor for Update 2. SET NOCOUNT ON 3. DECLARE @Id int 4. DECLARE @name varchar(50) 5. DECLARE Dynamic_cur_empupdate CURSOR

6. DYNAMIC 7. FOR 8. SELECT EmpID,EmpName from Employee ORDER BY EmpName 9. OPEN Dynamic_cur_empupdate 10. IF @@CURSOR_ROWS > 0 11. BEGIN 12. FETCH NEXT FROM Dynamic_cur_empupdate INTO @Id,@name 13. WHILE @@Fetch_status = 0 14. BEGIN 15. IF @name='Mohan' 16. Update Employee SET Salary=15000 WHERE CURRENT OF Dynamic_cur_empupdate 17. FETCH NEXT FROM Dynamic_cur_empupdate INTO @Id,@name 18. END 19. END 20. CLOSE Dynamic_cur_empupdate 21. DEALLOCATE Dynamic_cur_empupdate 22. SET NOCOUNT OFF 23. Go 24. Select * from Employee

1. -- Dynamic Cursor for DELETE 2. SET NOCOUNT ON 3. DECLARE @Id int 4. DECLARE @name varchar(50) 5. DECLARE Dynamic_cur_empdelete CURSOR 6. DYNAMIC 7. FOR 8. SELECT EmpID,EmpName from Employee ORDER BY EmpName 9. OPEN Dynamic_cur_empdelete 10. IF @@CURSOR_ROWS > 0 11. BEGIN 12. FETCH NEXT FROM Dynamic_cur_empdelete INTO @Id,@name 13. WHILE @@Fetch_status = 0 14. BEGIN 15. IF @name='Deepak' 16. DELETE Employee WHERE CURRENT OF Dynamic_cur_empdelete 17. FETCH NEXT FROM Dynamic_cur_empdelete INTO @Id,@name 18. END 19. END 20. CLOSE Dynamic_cur_empdelete 21. DEALLOCATE Dynamic_cur_empdelete 22. SET NOCOUNT OFF 23. Go 24. Select * from Employee

Forward Only Cursor - Example


1. --Forward Only Cursor for Update 2. SET NOCOUNT ON 3. DECLARE @Id int 4. DECLARE @name varchar(50) 5. DECLARE Forward_cur_empupdate CURSOR 6. FORWARD_ONLY 7. FOR 8. SELECT EmpID,EmpName from Employee ORDER BY EmpName 9. OPEN Forward_cur_empupdate 10. IF @@CURSOR_ROWS > 0 11. BEGIN 12. FETCH NEXT FROM Forward_cur_empupdate INTO @Id,@name 13. WHILE @@Fetch_status = 0 14. BEGIN 15. IF @name='Amit' 16. Update Employee SET Salary=24000 WHERE CURRENT OF Forward_cur_empupdate 17. FETCH NEXT FROM Forward_cur_empupdate INTO @Id,@name 18. END 19. END 20. CLOSE Forward_cur_empupdate 21. DEALLOCATE Forward_cur_empupdate 22. SET NOCOUNT OFF 23. Go 24. Select * from Employee

1. 2. 3. 4. 5. 6. 7. 8. 9.

-- Forward Only Cursor for Delete SET NOCOUNT ON DECLARE @Id int DECLARE @name varchar(50) DECLARE Forward_cur_empdelete CURSOR FORWARD_ONLY FOR SELECT EmpID,EmpName from Employee ORDER BY EmpName OPEN Forward_cur_empdelete

10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24.

IF @@CURSOR_ROWS > 0 BEGIN FETCH NEXT FROM Forward_cur_empdelete INTO @Id,@name WHILE @@Fetch_status = 0 BEGIN IF @name='Sonu' DELETE Employee WHERE CURRENT OF Forward_cur_empdelete FETCH NEXT FROM Forward_cur_empdelete INTO @Id,@name END END CLOSE Forward_cur_empdelete DEALLOCATE Forward_cur_empdelete SET NOCOUNT OFF Go Select * from Employee

Keyset Driven Cursor - Example


1. -- Keyset driven Cursor for Update 2. SET NOCOUNT ON 3. DECLARE @Id int 4. DECLARE @name varchar(50) 5. DECLARE Keyset_cur_empupdate CURSOR 6. KEYSET 7. FOR 8. SELECT EmpID,EmpName from Employee ORDER BY EmpName 9. OPEN Keyset_cur_empupdate 10. IF @@CURSOR_ROWS > 0 11. BEGIN 12. FETCH NEXT FROM Keyset_cur_empupdate INTO @Id,@name 13. WHILE @@Fetch_status = 0 14. BEGIN 15. IF @name='Pavan' 16. Update Employee SET Salary=27000 WHERE CURRENT OF Keyset_cur_empupdate 17. FETCH NEXT FROM Keyset_cur_empupdate INTO @Id,@name 18. END 19. END 20. CLOSE Keyset_cur_empupdate 21. DEALLOCATE Keyset_cur_empupdate 22. SET NOCOUNT OFF 23. Go 24. Select * from Employee

1. -- Keyse Driven Cursor for Delete 2. SET NOCOUNT ON 3. DECLARE @Id int 4. DECLARE @name varchar(50) 5. DECLARE Keyset_cur_empdelete CURSOR 6. KEYSET 7. FOR 8. SELECT EmpID,EmpName from Employee ORDER BY EmpName 9. OPEN Keyset_cur_empdelete 10. IF @@CURSOR_ROWS > 0 11. BEGIN 12. FETCH NEXT FROM Keyset_cur_empdelete INTO @Id,@name 13. WHILE @@Fetch_status = 0 14. BEGIN 15. IF @name='Amit' 16. DELETE Employee WHERE CURRENT OF Keyset_cur_empdelete 17. FETCH NEXT FROM Keyset_cur_empdelete INTO @Id,@name 18. END 19. END 20. CLOSE Keyset_cur_empdelete 21. DEALLOCATE Keyset_cur_empdelete 22. SET NOCOUNT OFF 23. Go Select * from Employee

SQL Server Basics of Cursors


Cursor is a database objects to retrieve data from a result set one row at a time, instead of the TSQL commands that operate on all the rows in the result set at one time. We use cursor when we need to update records in a database table in singleton fashion means row by row.

Life Cycle of Cursor Declare Cursor


A cursor is declared by defining the SQL statement that returns a result set.

Open
A Cursor is opened and populated by executing the SQL statement defined by the cursor.

Fetch
When cursor is opened, rows can be fetched from the cursor one by one or in a block to do data manipulation.

Close
After data manipulation, we should close the cursor explicitly.

Deallocate
Finally, we need to delete the cursor definition and released all the system resources associated with the cursor.
Syntax to Declare Cursor

Declare Cursor SQL Comaand is used to define the cursor with many options that impact the scalablity and loading behaviour of the cursor. The basic syntax is given below
1. 2. 3. 4. 5. 6. 7. DECLARE cursor_name CURSOR [LOCAL | GLOBAL] --define cursor scope [FORWARD_ONLY | SCROLL] --define cursor movements (forward/backward) [STATIC | KEYSET | DYNAMIC | FAST_FORWARD] --basic type of cursor [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] --define locks FOR select_statement --define SQL Select statement FOR UPDATE [col1,col2,...coln] --define columns that need to be updated

Syntax to Open Cursor

A Cursor can be opened locally or globally. By default it is opened locally. The basic syntax to open cursor is given below:
1. OPEN [GLOBAL] cursor_name --by default it is local

Syntax to Fetch Cursor

Fetch statement provides the many options to retrieve the rows from the cursor. NEXT is the default option. The basic syntax to fetch cursor is given below:
1. FETCH [NEXT|PRIOR|FIRST|LAST|ABSOLUTE n|RELATIVE n] 2. FROM [GLOBAL] cursor_name 3. INTO @Variable_name[1,2,..n]

Syntax to Close Cursor

Close statement closed the cursor explicitly. The basic syntax to close cursor is given below:
1. CLOSE cursor_name --after closing it can be reopen

Syntax to Deallocate Cursor

Deallocate statement delete the cursor definition and free all the system resources associated with the cursor. The basic syntax to close cursor is given below:
1. DEALLOCATE cursor_name --after deallocation it can't be reopen

SQL SERVER Simple Examples of Cursors


1. 2. 3. 4. 5. 6. 7. 8. 9. ( CREATE TABLE Employee EmpID int PRIMARY KEY, EmpName varchar (50) NOT NULL, Salary int NOT NULL, Address varchar (200) NOT NULL,

) GO INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida') 10. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi') 11. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun') 12. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida') 13. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon') 14. GO 15. SELECT * FROM Employee

1. 2. 3. 4. 5. 6.

SET NOCOUNT ON DECLARE @Id int DECLARE @name varchar(50) DECLARE @salary int DECLARE cur_emp CURSOR STATIC FOR

7. SELECT EmpID,EmpName,Salary from Employee 8. OPEN cur_emp 9. IF @@CURSOR_ROWS > 0 10. BEGIN 11. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary 12. WHILE @@Fetch_status = 0 13. BEGIN 14. PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+ ', Salary : '+convert(varchar(20),@salary) 15. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary 16. END 17. END 18. CLOSE cur_emp 19. DEALLOCATE cur_emp 20. SET NOCOUNT OFF

Stored Procedure Plan Recompilation and Performance Tuning


The main advantage of stored procedure is, to execute T-SQL statements in less time than the similar set of T-SQL statements is executed individually. The reason to take less time is that the query execution plan for the stored procedures is already stored in the "sys.procedures" system defined view. The recompilation process of stored procedure is like as compilation process and also reduce Sql Server performance. Stored procedure with recompilation option was introduced in Sql Server 2005. We should recompile stored procedure in following cases 1. Changing to the schema (means adding/dropping columns, constraints, rules, index, trigger etc) of the tables or referenced table(s) or view(s). 2. Updating the statistics used by the execution plan of stored procedure We have two options for stored procedure recompilation

Recompile option at the time of Creation


In this we create a stored procedure with RECOMPILE option. When we call this procedure than every time this procedure will be recompile before executing.

1. CREATE PROCEDURE usp_InsertEmployee 2. WITH RECOMPILE 3. @flag bit output,-- return 0 for fail,1 for success 4. @EmpID int, 5. @Name varchar(50), 6. @Salary int, 7. @Address varchar(100) 8. AS 9. BEGIN 10. BEGIN TRANSACTION 11. BEGIN TRY 12. Insert into Employee(EmpID,Name,Salary,Address) Values(@EmpID,@Name,@Salary,@Address); 13. set @flag=1; 14. commit TRANSACTION; 15. END TRY 16. BEGIN CATCH 17. rollback TRANSACTION; 18. set @flag=0; 19. END CATCH 20. END

21. 22.

Declare @flag bit --Now Execute this procedure. Every time this procedure will be recompiled 23. EXEC usp_InsertEmployee @flag output,1,'Deepak',14000,'Noida' 24. if @flag=1 25. print 'Successfully inserted' 26. else 27. print 'There is some error'

Recompile option at the time of Execution


In this we call a stored procedure with RECOMPILE option. Hence this stored procedure will be compiled only when we use RECOMPILE option at the time of calling. This is the best option for stored procedure recompilation.
28. 29. 30. 31. 32. 33. CREATE PROCEDURE usp_InsertEmployee @flag bit output,-- return 0 for fail,1 for success @EmpID int, @Name varchar(50), @Salary int, @Address varchar(100)

34. 35. 36. 37. 38.

AS BEGIN BEGIN TRANSACTION BEGIN TRY Insert into Employee(EmpID,Name,Salary,Address) Values(@EmpID,@Name,@Salary,@Address); 39. set @flag=1; 40. commit TRANSACTION; 41. END TRY 42. BEGIN CATCH 43. rollback TRANSACTION; 44. set @flag=0; 45. END CATCH 46. END

47. 48.

Declare @flag bit --Now Execute this procedure with RECOMPILE option, if you want to recompile its execution plan 49. EXEC usp_InsertEmployee @flag output,2,'Jitendra',15000,'Noida' WITH RECOMPILE 50. if @flag=1 51. print 'Successfully inserted' 52. else 53. print 'There is some error'

Note

1. Creating the stored procedure by using "WITH RECOMPILE" option force the SQL Server to recompile the stored procedure every time when it is called. 2. Call the stored procedure by using "WITH RECOMPILE" option in the EXEC command. 3. Altering the procedure will cause the SQL Server to create a new execution plan 4. If SQL Server is restarted or stopped then all the execution plans will be flush from server cache and recreated when the stored procedure is executed after restarting the server. 5. The "Sp_recompile" system defined stored procedure can be called to refresh the query execution plan for a particular stored procedure

Different Types of SQL Server Functions

Function is a database object in Sql Server. Basically it is a set of sql statements that accepts only input parameters, perform actions and return the result. Function can return only single value or a table. We cant use function to Insert, Update, Delete records in the database table(s). For more about stored procedure and function refer the article Difference between Stored Procedure and Function

Types of Function System Defined Function


These functions are defined by Sql Server for different purpose. We have two types of system defined function in Sql Server

Scalar Function
Scalar functions operates on a single value and returns a single value. Below is the list of some useful Sql Server Scalar functions.
System Scalar Function Scalar Function Description abs(-10.67) This returns absolute number of the given number means 10.67. rand(10) This will generate random number of 10 characters. round(17.56719,3) This will round off the given number to 3 places of decimal means 17.567 upper('dotnet') This will returns upper case of given string means 'DOTNET' lower('DOTNET') This will returns lower case of given string means 'dotnet'

ltrim(' dotnet') This will remove the spaces from left hand side of 'dotnet' string. convert(int, 15.56) This will convert the given float value to integer means 15.

Aggregate Function
Aggregate functions operates on a collection of values and returns a single value. Below is the list of some useful Sql Server Aggregate functions.
System Aggregate Function Aggregate Function Description max() This returns maximum value from a collection of values. min() This returns minimum value from a collection of values. avg() This returns average of all values in a collection. count() This returns no of counts from a collection of values.

User Defined Function


These functions are created by user in system database or in user defined database. We three types of user defined functions.

Scalar Function
User defined scalar function also returns single value as a result of actions perform by function. We return any datatype value from function.

1. --Create a table CREATE TABLE Employee 2. ( 3. EmpID int PRIMARY KEY, 4. FirstName varchar(50) NULL, 5. LastName varchar(50) NULL, 6. Salary int NULL, 7. Address varchar(100) NULL, 8. ) 9. --Insert Data 10. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(1,'Mohan','Chauahn',22000,'Delhi'); 11. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(2,'Asif','Khan',15000,'Delhi'); 12. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(3,'Bhuvnesh','Shakya',19000,'Noida'); 13. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(4,'Deepak','Kumar',19000,'Noida'); 14. --See created table 15. Select * from Employee

16.

--Create function to get emp full name Create function fnGetEmpFullName 17. ( 18. @FirstName varchar(50), @LastName varchar(50) 19. ) 20. returns varchar(101) 21. As 22. Begin return (Select @FirstName + ' '+ @LastName); 23. end

24. 25.

--Now call the above created function Select dbo.fnGetEmpFullName(FirstName,LastName) as Name, Salary from Employee

Inline Table-Valued Function


User defined inline table-valued function returns a table variable as a result of actions perform by function. The value of table variable should be derived from a single SELECT statement.
26. 27. 28. 29. 30. --Create function to get employees Create function fnGetEmployee() returns Table As return (Select * from Employee)

31. 32.

--Now call the above created function Select * from fnGetEmployee()

Multi-Statement Table-Valued Function


User defined multi-statement table-valued function returns a table variable as a result of actions perform by function. In this a table variable must be explicitly declared and defined whose value can be derived from a multiple sql statements.
33. --Create function to EmpID,FirstName and Salary of Employee 34. Create function fnGetMulEmployee() 35. returns @Emp Table 36. ( 37. EmpID int, FirstName varchar(50), 38. Salary int 39. ) 40. As 41. begin

42.

Insert @Emp Select e.EmpID,e.FirstName,e.Salary from Employee e; 43. --Now update salary of first employee 44. update @Emp set Salary=25000 where EmpID=1; 45. --It will update only in @Emp table not in Original Employee table 46. return 47. end

48. 49.

--Now call the above created function Select * from fnGetMulEmployee()

50.

--Now see the original table. This is not affected by above function update command 51. Select * from Employee

Note

1. Unlike Stored Procedure, Function returns only single value. 2. Unlike Stored Procedure, Function accepts only input parameters. 3. Unlike Stored Procedure, Function is not used to Insert, Update, Delete data in database table(s). 4. Like Stored Procedure, Function can be nested up to 32 level. 5. User Defined Function can have upto 1023 input parameters while a Stored Procedure can have upto 21000 input parameters. 6. User Defined Function can't returns XML Data Type. 7. User Defined Function doesn't support Exception handling. 8. User Defined Function can call only Extended Stored Procedure. 9. User Defined Function doesn't support set options like set ROWCOUNT etc.

SQL Server XML Data Type


xml data type was introduced in SQL Server 2005 to work with XML data. Using this data type, we can store XML in its native format and can also query/modify the xml data within the xml. We can use xml data type like as: 1. 2. 3. 4. Variable Field/Column in a table Parameter in the user-defined function (UDF) or stored procedure(SP) return value from a UDF or SP

We can define xml data type field to NOT NULL or we can provide a default value to it.

Limitation Of XML Data type


1. We cant directly compare an instance of the XML data type to another instance of the XML data type. For equality comparisons we first need to convert the XML type to a character type. 2. We cant use GROUP BY or ORDER BY with an XML data type column. 3. We cant use XML data type field as a primary key, Unique key and foreign key. 4. We cant define XML data type field with COLLATE keyword.

Query XML Data


Suppose we have following tables in database. Using these tables we will produce query result as an xml
CREATE TABLE Department ( DeptID int IDENTITY(1,1) primary key , DeptName varchar(50) NULL, Location varchar(50) NULL ) CREATE TABLE Employee ( EmpID int IDENTITY(1,1) NOT NULL, EmpName varchar(50) NULL, Address varchar(100) NULL, DeptID int foreign Key references Department(DeptID) ) --Now Insert data into these tables INSERT INTO Department (DeptName,Location)VALUES('HR','Delhi') INSERT INTO Department (DeptName,Location)VALUES('IT','Delhi') INSERT INTO Department (DeptName,Location)VALUES('Technical','Delhi') INSERT INTO Employee( EmpName,Address,DeptID)VALUES('Shailendra','Noida',2) INSERT INTO Employee( EmpName,Address,DeptID)VALUES('Mohan','Noida',2) INSERT INTO Employee( EmpName,Address,DeptID)VALUES('Vipul','Noida',1) INSERT INTO Employee( EmpName,Address,DeptID)VALUES('Mrinal','Noida',3)

We can retrieve data table records as xml data using FORXML clause in SELECT statement. In FORXML Clause we can define three xml mode.

AUTO
It generates output with both element and attribute features in combination with a sub query.
SELECT DeptName, EmpID FROM Employee AS Emp JOIN Department AS Dept ON Emp.DeptID= Dept.DeptID FOR XML AUTO;

Output:
<Dept DeptName="IT"> <Emp EmpID="1" /> <Emp EmpID="2" /> </Dept> <Dept DeptName="HR"> <Emp EmpID="3" /> </Dept> <Dept DeptName="Technical"> <Emp EmpID="4" /> <Emp EmpID="5" /> </Dept>

EXPLICIT
It converts the rowset that is result of the query execution, into an XML document. This mode provides more control over the format of the XML means in which format you want xml you need to define that format in select query.
SELECT 1 tag, NULL parent, EmpID [employee!1!ID], EmpName [employee!1!name], NULL [order!2!date], NULL [department!3!name] FROM Employee UNION ALL SELECT 3, 1, EmpID, NULL, NULL, DeptName FROM Employee e JOIN Department d ON e.DeptID=d.DeptID ORDER BY 3, 1 FOR XML EXPLICIT;

Output

<employee ID="1" name="Shailendra"> <department name="IT" /> </employee> <employee ID="2" name="Mohan"> <department name="IT" /> </employee> <employee ID="3" name="Vipul"> <department name="HR" /> </employee> <employee ID="4" name="Mrinal"> <department name="Technical" /> </employee> <employee ID="5" name="Jitendra"> <department name="Technical" /> </employee>

RAW
It produce a single element or the optionally provided element name for each row in the query result set that is returned by select statement.
SELECT Emp.EmpID, Dept.DeptName Employee as Emp JOIN Department as Dept ON Emp.DeptID= Dept.DeptID FOR XML RAW;

Output
<row EmpID="1" DeptName="IT" /> <row EmpID="2" DeptName="IT" /> <row EmpID="3" DeptName="HR" /> <row EmpID="4" DeptName="Technical" /> <row EmpID="5" DeptName="Technical" />

SQL Server XQuery Methods


Sql Server provides xquery methods to query xml file or xml data. Using these methods we can Insert, Update, Delete data in xml file or in XML Data Type variable. In Sql Server XQuery statements are case sensitive since xml is case sensitive. Hence while query to xml data remember this thing.

XQuery Methods
we have following xml data to implement all the XQuery methods given below.

xml.exist()
This method returns a boolean value depends upon the condition in this method like as
1. SELECT @xml.exist('/Suppliers/User[@Email = "bipul.tiwari@ymail.com"]') as Result1 2. SELECT @xml.exist('/Suppliers/User[@Email = "bipul.tiwari@yahoo.com"]') as Result2

xml.query()
This method takes an XQuery statement and returns an instance of the XML data type like as
3. SELECT @xml.query('/Suppliers/User') as Users

4.

SELECT @xml.query('distinctvalues( data(/Suppliers/User/Item/@No))') as Items

xml.value()
This method takes an XQuery statement and returns a single value after type casting like as
5. SELECT @xml.value('/Suppliers[1]/User[1]/@Email', 'VARCHAR(20)') as ResultEmail1 6. SELECT @xml.value('/Suppliers[1]/User[2]/@Email', 'VARCHAR(20)') as ResultEmail2

xml.nodes()
This method takes an XQuery statement and returns a single value after type casting like as
7. SELECT x.value('@UserNo', 'int') AS UserNo, x.value('@Email', 'varchar(50)') AS Email

8. FROM @xml.nodes('/Suppliers/User') TempXML (x) 9. SELECT x.value('../@UserNo', 'int') AS UserNo, x.value('../@Email', 'varchar(50)') AS Email, x.value('@Name', 'varchar(50)') AS ItemName 10. FROM @xml.nodes('/Suppliers/User/Item') TempXML (x)

xml.modify()
This method takes an XQuery statement and modify the xml data like as
11. 12. 13. --Insert node in the end of XML SET @xml.modify ('insert as last into (/Suppliers)[1]') SELECT @xml;

14. 15. 16.

--Update node in xml DECLARE @UserNo int =120 SET @xml.modify ('replace value of (/Suppliers/User/@UserNo) [1] with sql:variable("@UserNo")') 17. SELECT @xml;

18. 19.

--Update node in xml conditionally SET @xml.modify(' replace value of (/Suppliers/User/@UserNo) [1] with ( if (count(/Suppliers/User[1]/Item) > 2) then "3.0" else "1.0" ) ')

20.

SELECT @xml;

21.

--Delete node in xml SET @xml.modify(' delete Suppliers/User/Item[@No=1]') 22. SELECT @xml;

23. 24. 25.

--Delete node in xml depends on condition DECLARE @ItemNo int=1 SET @xml.modify(' delete Suppliers/User/Item[@No=sql:variable("@ItemNo")]') 26. SELECT @xml;

SQL Injection Attacks


A SQL Injection attack is an attack mechanisms used by hackers to steal sensitive information from database of an organization. It is the application layer means front-end attack which takes benefit of inappropriate coding of our applications that allows hacker to insert SQL commands into your code that is using sql statement. SQL Injection arises since the fields available for user input allow SQL statements to pass through and query the database directly.

SQL Injection: A Simple Example


For explaining this issue, Let's create a table "tbluser" for describing the SQL Injection Attack.
( Create table tbluser

userName varchar(50) primary key, userpwd varchar(50), address varchar(100) ) insert into tbluser(userName,userpwd,address)values('mohan@gmail.com','123456','Delhi'); insert into tbluser(userName,userpwd,address)values('shailendra@gmail.com','123456','Noid a'); insert into tbluser(userName,userpwd,address)values('jitendra@gmail.com','123456','Gurgao n'); insert into tbluser(userName,userpwd,address)values('bipul@gmail.com','123456','Delhi'); select * from tbluser

Now lets look at the following query string in Asp.net. In this we are passing username from TextBox "txtUserID" and userpwd from TextBox "txtpwd" to check user credential.

"SELECT * FROM tbluser WHERE userName = '"+ txtUserID.text +"' and userpwd = '"+ txtPwd.text +"'";

Now hacker will pass the following input to TextBoxes to inject sql attack. What will happen when the below data goes as input?
"SELECT * FROM tbluser WHERE userName = ';Drop table tblusers --' and userpwd = '123'";

Semicolon ; in above statement will terminate the current sql. So, "SELECT * FROM tbluser WHERE UserID = ''" will become a separate statement and after Semi Colon ; it will starts a new sql statement "Drop table tblusers" that will drop our table tbluser. Hence your user details table has been dropped and your database will be unmanaged.

Solution for SQL Injection Attack


1. In C# or VB.Net during building a SQL Statement, use the SqlParameter to define the Parameter Name, type, and value instead of making a straight command like as above 2. In Asp.Net query specify that CommandType as Text or Stored Procedure. 3. When we use Parameters Collection, we should use parameters the type and size will also be mention. 4. If we use stored procedure, instead of directly building by using Exec command, use sp_executesql command. 5. Another way to stop SQL injection attacks is to filter the user input for SQL characters. Use the REPLACE function to replace any apostrophe (single quotation mark to SQL) with an additional apostrophe. Within a SQL string, two consecutive single quotation marks are treated as an instance of the apostrophe character within the string.

SQL Server System Defined Database


SQL Server 2008 and 2005 have five system defined databases: master, model, tempdb, msdb, and resource. These databases are used by SQL Server for its own operation and management. Lets see these database use and function.

Master Database
1. Master database contains all of the System level information for Sql Server. 2. It contains all system configuration settings details for Sql Server. We can see the system configuration information by using the system defined "SYSCONFIGURES" table.
Select * from SYSCONFIGURES

3. It contains all existing databases details for Sql Server. We can see the database information and where the actual file persists by using the system defined "SYSDATABASES" table

Select * from SYSDATABASES

4. It contains all login accounts details for Sql Server. We can see the login account information by using the system defined "SYSXLOGINS" table.
Select * from SYSXLOGINS

5. It contains all users details for Sql Server. We can see the user information by using the system defined "SYSUSERS" table
Select * from SYSUSERS

6. Primary data of Master database is stored in master.mdf file which default size is 11 MB and Master database log is stored in Masterlog.ldf file which default size is 1.25 MB.

TempDB Database
1. TempDB databse contains all temporary objects like temporary tables and temporary stored procedures for Sql Server.The temporary objects are created by preceding # to the temporary object name. Example#tEmp table gets created in school database.
Use School CREATE TABLE #tEmp ( EmpID int EmpName Varchar(50) )

When the above TSQL statement gets executed, if we see at the tempDB, this temporary table will exist there. Note that we create this table in School Database. But it exists in tempDB. We can access #tEmp table from any other database. 2. TempDB database is recreated every time when we re-start the SQL Server. Hence, when the database server gets restarted, the temporary objects will be removed from TempDB database. 3. Primary data of TempDB database is stored in tempDB.mdf file which default size is 8 MB and TempDB database log is stored in templog.ldf file which default size is 0.5MB.

Model Database
1. Model database work as a template for all the databases created on Sql Server. 2. If we want to keep some generic database objects like as tables, function stored procedures into the newly created database then we put these objects into Model database. Hence when we create a new database then available databse objects in Model database, would be copied into newly created database.

Note : At the creation of a new database,if any database connection is opened for Model database then We can not able to create new database. 3. Primary data of Model database is stored in model.mdf file which default size is 0.75 MB and Model database log is stored in modellog.ldf which default size is 0.75MB.

MSDB Database
1. MSDB database is used by SQL Server Agent to schedule alerts, jobs, and to record operators. Example If we create a Database Maintenance Plan to take backup of a particular database on daily basis, then each and every entry will be stored in system defined SYSJOBS table in MSDB Database. 2. Primary data of Msdb database is stored in msdbdata.mdf file which default size is 12 MB and Msdb database log is stored in msdblog.ldf which default size is 2.25MB.

Resource Database
1. Resource database is also a system defined database that is hidden from user view like as another system defined database. It contains the system defined objects. 2. We can see the Resource database file by navigating to C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn. 3. Using the OBJECT_DEFINITION system function, we can view the contents of the resource database.
SELECT OBJECT_DEFINITION(OBJECT_ID('sys.objects'))

After Trigger, Instead of Trigger Example


Triggers are special type of stored procedure that automatically execute when a DDL or DML statement associated with the trigger is executed. DML Triggers are used to evaluate data after data manipulation using DML statements. We have two types of DML triggers.

Types of DML Triggers After Trigger (using FOR/AFTER CLAUSE)


This trigger fires after SQL Server completes the execution of the action successfully that fired it. Example :If you insert record/row in a table then the trigger associated with the insert event on this table will fire only after the row passes all the checks, such as primary key,

rules, and constraints. If the record/row insertion fails, SQL Server will not fire the After Trigger.

Instead of Trigger (using INSTEAD OF CLAUSE)


This trigger fires before SQL Server starts the execution of the action that fired it. This is much more different from the AFTER trigger, which fires after the action that caused it to fire. We can have an INSTEAD OF insert/update/delete trigger on a table that successfully executed but does not include the actual insert/update/delet to the table. Example :If you insert record/row in a table then the trigger associated with the insert event on this table will fire before the row passes all the checks, such as primary key, rules, and constraints. If the record/row insertion fails, SQL Server will fire the Instead of Trigger.

Example
1. -- First create table Employee_Demo 2. CREATE TABLE Employee_Demo 3. ( 4. Emp_ID int identity, 5. Emp_Name varchar(55), 6. Emp_Sal decimal (10,2) 7. ) 8. -- Now Insert records 9. Insert into Employee_Demo values ('Amit',1000); 10. Insert into Employee_Demo values ('Mohan',1200); 11. Insert into Employee_Demo values ('Avin',1100); 12. Insert into Employee_Demo values ('Manoj',1300); 13. Insert into Employee_Demo values ('Riyaz',1400); 14. --Now create table Employee_Demo_Audit for logging/backup purpose of table Employee_Demo create table Employee_Demo_Audit 15. ( 16. Emp_ID int, 17. Emp_Name varchar(55), 18. Emp_Sal decimal(10,2), 19. Audit_Action varchar(100), 20. Audit_Timestamp datetime 21. )

Now I am going to explain the use of After Trigger using Insert, Update, Delete statement with example

After Insert Trigger


1. -- Create trigger on table Employee_Demo for Insert statement 2. CREATE TRIGGER trgAfterInsert on Employee_Demo 3. FOR INSERT 4. AS declare @empid int, @empname varchar(55), @empsal decimal(10,2), @audit_action varchar(100); 5. select @empid=i.Emp_ID from inserted i; 6. select @empname=i.Emp_Name from inserted i;

7. select @empsal=i.Emp_Sal from inserted i; 8. set @audit_action='Inserted Record -- After Insert Trigger.'; insert into Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Ti mestamp) 9. values (@empid,@empname,@empsal,@audit_action,getdate()); 10. PRINT 'AFTER INSERT trigger fired.' 11. --Output will be

12. 13.

--Now try to insert data in Employee_Demo table insert into Employee_Demo(Emp_Name,Emp_Sal)values ('Shailu',1000); 14. --Output will be

15. 16. 17. 18.

--now select select * from select * from --Output will

data from both the tables to see trigger action Employee_Demo Employee_Demo_Audit be

Trigger have inserted the new record to Employee_Demo_Audit table for insert statement. In this way we can trace a insert activity on a table using trigger.

After Update Trigger


19. -- Create trigger on table Employee_Demo for Update statement

20. 21. 22. 23.

CREATE TRIGGER trgAfterUpdate ON dbo.Employee_Demo FOR UPDATE AS declare @empid int, @empname varchar(55), @empsal decimal(10,2), @audit_action varchar(100); 24. select @empid=i.Emp_ID from inserted i; 25. select @empname=i.Emp_Name from inserted i; 26. select @empsal=i.Emp_Sal from inserted i; if update(Emp_Name) 27. set @audit_action='Update Record --- After Update Trigger.'; 28. if update (Emp_Sal) 29. set @audit_action='Update Record --- After Update Trigger.'; 30. insert intoEmployee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audi t_Timestamp) 31. values (@empid,@empname,@empsal,@audit_action,getdate()); 32. PRINT 'AFTER UPDATE trigger fired.' 33. --Output will be

34. 35. 36.

--Now try to upadte data in Employee_Demo table update Employee_Demo set Emp_Name='Pawan' Where Emp_ID =6; --Output will be

37. 38. 39. 40.

--now select select * from select * from --Output will

data from both the tables to see trigger action Employee_Demo Employee_Demo_Audit be

Trigger have inserted the new record to Employee_Demo_Audit table for update statement. In this way we can trace a update activity on a table using trigger.

After Delete Trigger


41. 42. 43. 44. 45. -- Create trigger on table Employee_Demo for Delete statement CREATE TRIGGER trgAfterDelete ON dbo.Employee_Demo FOR DELETE AS declare @empid int, @empname varchar(55), @empsal decimal(10,2), @audit_action varchar(100); select @empid=d.Emp_ID FROM deleted d; 46. select @empname=d.Emp_Name from deleted d; 47. select @empsal=d.Emp_Sal from deleted d; 48. select @audit_action='Deleted -- After Delete Trigger.'; 49. insert into Employee_Demo_Audit (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 50. values (@empid,@empname,@empsal,@audit_action,getdate()); 51. PRINT 'AFTER DELETE TRIGGER fired.' 52. --Output will be

53. 54. 55.

--Now try to delete data in Employee_Demo table DELETE FROM Employee_Demo where emp_id = 5 --Output will be

56. 57. 58. 59.

--now select select * from select * from --Output will

data from both the tables to see trigger action Employee_Demo Employee_Demo_Audit be

Trigger have inserted the new record to Employee_Demo_Audit table for delete statement. In this way we can trace a delete activity on a table using trigger. Now I am going to explain the use of Instead of Trigger using Insert, Update, Delete statement with example

Instead of Insert Trigger


1. 2. 3. 4. 5. -- Create trigger on table Employee_Demo for Insert statement CREATE TRIGGER trgInsteadOfInsert ON dbo.Employee_Demo INSTEAD OF Insert AS declare @emp_id int, @emp_name varchar(55), @emp_sal decimal(10,2), @audit_action varchar(100); 6. select @emp_id=i.Emp_ID from inserted i; 7. select @emp_name=i.Emp_Name from inserted i; 8. select @emp_sal=i.Emp_Sal from inserted i; 9. SET @audit_action='Inserted Record -- Instead Of Insert Trigger.'; 10. BEGIN 11. BEGIN TRAN 12. SET NOCOUNT ON 13. if(@emp_sal>=1000) 14. begin 15. RAISERROR('Cannot Insert where salary < 1000',16,1); ROLLBACK; end 16. else begin Insert into Employee_Demo (Emp_Name,Emp_Sal) values (@emp_name,@emp_sal); Insert into Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Ti mestamp) values(@@identity,@emp_name,@emp_sal,@audit_action,getdate());

17. 18. 19. 20.

COMMIT; PRINT 'Record Inserted -- Instead Of Insert Trigger.' END --Output will be

21. 22. 23.

--Now try to insert data in Employee_Demo table insert into Employee_Demo values ('Shailu',1300) insert into Employee_Demo values ('Shailu',900) -- It will raise error since we are checking salary >=1000 24. --Outputs will be

25. 26. 27. 28.

--now select select * from select * from --Output will

data from both the tables to see trigger action Employee_Demo Employee_Demo_Audit be

Trigger have inserted the new record to Employee_Demo_Audit table for insert statement. In this way we can apply business validation on the data to be inserted using Instead of trigger and can also trace a insert activity on a table.

Instead of Update Trigger


29. 30. 31. 32. 33. -- Create trigger on table Employee_Demo for Update statement CREATE TRIGGER trgInsteadOfUpdate ON dbo.Employee_Demo INSTEAD OF Update AS declare @emp_id int, @emp_name varchar(55), @emp_sal decimal(10,2), @audit_action varchar(100); 34. select @emp_id=i.Emp_ID from inserted i; 35. select @emp_name=i.Emp_Name from inserted i; 36. select @emp_sal=i.Emp_Sal from inserted i; 37. BEGIN 38. BEGIN TRAN 39. if(@emp_sal>=1000) 40. begin 41. RAISERROR('Cannot Insert where salary < 1000',16,1); ROLLBACK; end 42. else begin 43. insert into Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Ti mestamp) values(@emp_id,@emp_name,@emp_sal,@audit_action,getdate()); 44. COMMIT; 45. PRINT 'Record Updated -- Instead Of Update Trigger.'; END 46. --Output will be

47. 48.

--Now try to upadte data in Employee_Demo table update Employee_Demo set Emp_Sal = '1400' where emp_id = 6

49. 50.

update Employee_Demo set Emp_Sal = '900' where emp_id = 6 --Output will be

51. 52. 53. 54.

--now select select * from select * from --Output will

data from both the tables to see trigger action Employee_Demo Employee_Demo_Audit be

Trigger have inserted the updated record to Employee_Demo_Audit table for update statement. In this way we can apply business validation on the data to be updated using Instead of trigger and can also trace a update activity on a table.

Instead of Delete Trigger


55. 56. 57. 58. 59. -- Create trigger on table Employee_Demo for Delete statement CREATE TRIGGER trgAfterDelete ON dbo.Employee_Demo INSTEAD OF DELETE AS declare @empid int, @empname varchar(55), @empsal decimal(10,2), @audit_action varchar(100); select @empid=d.Emp_ID FROM deleted d; 60. select @empname=d.Emp_Name from deleted d; 61. select @empsal=d.Emp_Sal from deleted d; 62. BEGIN TRAN if(@empsal>1200) begin 63. RAISERROR('Cannot delete where salary > 1200',16,1); 64. ROLLBACK; 65. end 66. else begin 67. delete from Employee_Demo where Emp_ID=@empid; 68. COMMIT; 69. insert into Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Ti mestamp) 70. values(@empid,@empname,@empsal,'Deleted -- Instead Of Delete Trigger.',getdate()); 71. PRINT 'Record Deleted -- Instead Of Delete Trigger.' end END 72. --Output will be

73. 74. 75. 76.

--Now try to delete data in Employee_Demo table DELETE FROM Employee_Demo where emp_id = 1 DELETE FROM Employee_Demo where emp_id = 3 --Output will be

77. 78. 79.

--now select data from both the tables to see trigger action select * from Employee_Demo select * from Employee_Demo_Audit

80.

--Output will be

Trigger have inserted the deleted record to Employee_Demo_Audit table for delete statement. In this way we can apply business validation on the data to be deleted using Instead of trigger and can also trace a delete activity on a table.

Different Types of SQL Server Triggers


Triggers are database object. Basically these are special type of stored procedure that are automatically fired/executed when a DDL or DML command statement related with the trigger is executed. Triggers are used to assess/evaluate data before or after data modification using DDL and DML statements. These are also used to preserve data integrity, to control server operations, to audit a server and to implement business logic or business rule.

Types of Triggers
In Sql Server we can create four types of triggers Data Definition Language (DDL) triggers, Data Manipulation Language (DML) triggers, CLR triggers and Logon triggers.

DDL Triggers
In SQL Server we can create triggers on DDL statements (like CREATE, ALTER, and DROP) and certain system defined stored procedures that perform DDL-like operations. Example : If you are going to execute the CREATE LOGIN statement or the sp_addlogin stored procedure to create login user, then both these can execute/fire a DDL trigger that you can create on CREATE_LOGIN event of Sql Server. We can use only FOR/AFTER clause in DDL triggers not INSTEAD OF clause means we can make only After Trigger on DDL statements.

DDL trigger can be used to observe and control actions performed on the server, and to audit these operations. DDL triggers can be used to manage administrator tasks such as auditing and regulating database operations.

DML Triggers
In SQL Server we can create triggers on DML statements (like INSERT, UPDATE, and DELETE) and stored procedures that perform DML-like operations. DML Triggers are of two types

After Trigger (using FOR/AFTER CLAUSE)


This type of trigger fires after SQL Server finish the execution of the action successfully that fired it. Example : If you insert record/row in a table then the trigger related/associated with the insert event on this table will fire only after the row passes all the constraints, like as primary key constraint, and some rules. If the record/row insertion fails, SQL Server will not fire the After Trigger.

Instead of Trigger (using INSTEAD OF CLAUSE)


This type of trigger fires before SQL Server starts the execution of the action that fired it. This is differ from the AFTER trigger, which fires after the action that caused it to fire. We can have an INSTEAD OF insert/update/delete trigger on a table that successfully executed but does not include the actual insert/update/delete to the table. Example : If you insert record/row in a table then the trigger related/associated with the insert event on this table will fire before the row passes all the constraints, such as primary key constraint and some rules. If the record/row insertion fails, SQL Server will fire the Instead of Trigger.

CLR Triggers
CLR triggers are special type of triggers that based on the CLR (Common Language Runtime) in .net framework. CLR integration of triggers has been introduced with SQL Server 2008 and allows for triggers to be coded in one of .NET languages like C#, Visual Basic and F#. We coded the objects(like trigger) in the CLR that have heavy computations or need references to objects outside the SQL Server. We can write code for both DDL and DML triggers, using a supported CLR language like C#, Visual basic and F#. I will discuss CLR trigger later.

Logon Triggers

Logon triggers are special type of trigger that fire when LOGON event of Sql Server is raised. This event is raised when a user session is being established with Sql Server that is made after the authentication phase finishes, but before the user session is actually established. Hence, all messages that we define in the trigger such as error messages, will be redirected to the SQL Server error log. Logon triggers do not fire if authentication fails. We can use these triggers to audit and control server sessions, such as to track login activity or limit the number of sessions for a specific login. Synatx for Logon Trigger
1. 2. 3. 4. 5. 6. CREATE TRIGGER trigger_name ON ALL SERVER [WITH ENCRYPTION] {FOR|AFTER} LOGON AS sql_statement [1...n ]

Syntax for Trigger


1. 2. 3. 4. 5. 6. 7. CREATE TRIGGER trigger_name ON {table|view} [WITH ENCRYPTION|EXECUTE AS] {FOR|AFTER|INSTEAD OF} {[CREATE|ALTER|DROP|INSERT|UPDATE|DELETE ]} [NOT FOR REPLICATION] AS sql_statement [1...n ]

trigger_name
This is the name of the trigger. It should conform to the rules for identifiers in Sql Server.

table|view
This is the table/view on which the trigger is to be created.

ENCRYPTION
This option is optional. If this option is specified, original text of the CREATE TRIGGER statement will be encrypted.

EXECUTE AS
This option is optional. This option specifies, the security context under which the trigger is executed.

FOR/AFTER

FOR/AFTER specifies that the trigger is After Trigger. AFTER is the default, if FOR is the only keyword specified.AFTER triggers cannot be defined on views.

INSTEAD OF
INSTEAD OF specifies that the trigger is Instead Of Trigger.

CREATE|ALTER|DROP|INSERT|UPDATE|DELETE
These keywords specify on which action the trigger should be fired. One of these keywords or any combination of these keywords in any order can be used.

NOT FOR REPLICATION


Indicates that the trigger should not be executed when a replication process modifies the table involved in the trigger.

AS
After this we specifies the actions and condition that the trigger perform.

sql_statement
These are the trigger conditions and actions. The trigger actions specified in the T-SQL statements.
Note

1. The name of a trigger should follow the rules for identifiers. 2. DML trigger can be composed by any T-SQL statements, except CREATE DATABASE, ALTER DATABASE, DROP DATABASE, LOAD DATABASE, LOAD LOG, RECONFIGURE, RESTORE DATABASE, and RESTORE LOG statements. 3. You cannot create triggers against system tables or dynamic management views. Moreover, the TRUNCATE TABLE statement does not fire a trigger because this operation does not log individual row deletions. 4. If you use the DATABASE option, the scope of your DDL trigger will be the current database. If you use the ALL SERVER option, the scope of your DDL triggers to the current server. 5. AFTER triggers cannot be defined on views. 6. AFTER is the default, if FOR is the only keyword specified.

SQL Server Transactions Management


A transaction is a set of T-SQL statements that are executed together as a unit like as a single TSQL statement. If all of these T-SQL statements executed successfully, then a transaction is

committed and the changes made by T-SQL statements permanently saved to database. If any of these T-SQL statements within a transaction fail, then the complete transaction is cancelled/ rolled back. We use transaction in that case, when we try to modify more than one tables/views that are related to one another. Transactions affect SQL Server performance greatly. Since When a transaction is initiated then it locks all the tables data that are used in the transaction. Hence during transaction life cycle no one can modify these tables data that are used by the transaction. The reason behind the locking of the data is to maintain Data Integrity.

Types of Transactions Implicit Transaction


Implicit transactions are maintained by SQL Server for each and every DDL (CREATE, ALTER, DROP, TRUNCATE), DML (INSERT, UPDATE, DELETE) statements. All these T-SQL statements runs under the implicit transaction. If there is an error occurs within these statements individually, SQL Server will roll back the complete statement.

Explicit Transaction
Explicit transactions are defined by programmers. In Explicit transaction we include the DML statements that need to be execute as a unit. Since SELECT statements doesnt modify data. Hence generally we dont include Select statement in a transaction.

Transactions Example
1. CREATE TABLE Department 2. ( 3. DeptID int PRIMARY KEY, 4. DeptName varchar(50) NULL, 5. Location varchar(100) NULL, 6. ) 7. GO 8. CREATE TABLE Employee 9. ( 10. EmpID int PRIMARY KEY, 11. Name varchar(50) NULL, 12. Salary int NULL, 13. Address varchar(100) NULL, 14. DeptID int foreign Key references Department(DeptID) 15. )

1. --Now Insert data 2. INSERT INTO Department(DeptID,DeptName,Location)VALUES(1,'IT','Delhi')

3. GO 4. INSERT INTO Employee(EmpID,Name,Salary,Address,DeptID)VALUES(1,'Mohan',15000,'Delhi' ,1) 5. SELECT * FROM Department 6. SELECT * FROM Employee

1. BEGIN TRANSACTION trans 2. BEGIN TRY 3. INSERT INTO Department(DeptID,DeptName,Location)VALUES(2,'HR','Delhi') 4. INSERT INTO Employee(EmpID,Name,Salary,Address,DeptID)VALUES(1,'Mohan',18000,'Delhi' ,1) 5. IF @@TRANCOUNT > 0 6. BEGIN COMMIT TRANSACTION trans 7. END 8. END TRY 9. BEGIN CATCH 10. print 'Error Occured' 11. IF @@TRANCOUNT > 0 12. BEGIN ROLLBACK TRANSACTION trans 13. END 14. END CATCH

1. --Now Select data to see transaction affects 2. SELECT * FROM Employee 3. SELECT * FROM Department

1. --Transaction with Save Point BEGIN TRANSACTION trans 2. BEGIN TRY 3. INSERT INTO Department(DeptID,DeptName,Location)VALUES(2,'HR','Delhi') 4. IF @@TRANCOUNT > 0

5. BEGIN SAVE TRANSACTION trans; 6. END 7. INSERT INTO Department(DeptID,DeptName,Location)VALUES(3,'Admin','Delhi') 8. INSERT INTO Employee(EmpID,Name,Salary,Address,DeptID)VALUES(1,'Mohan',18000,'Delhi' ,1) 9. IF @@TRANCOUNT > 0 10. BEGIN COMMIT TRANSACTION trans 11. END 12. END TRY 13. BEGIN CATCH 14. print 'Error Occured' 15. IF @@TRANCOUNT > 0 16. BEGIN ROLLBACK TRANSACTION trans 17. END 18. END CATCH

1. --Now Select data to see transaction affects 2. SELECT * FROM Employee 3. SELECT * FROM Department

Definition, Use of Group by and Having Clause


In Sql Server, we have group by clause for grouping the records of the database table according to our need. We use having clause to filter data that we get from group by clause.Having clause operates only on group by clause means to use having clause we need to use group by clause first. Lets go through both the clauses.

Group By Clause
Group By clause is used for grouping the records of the database table(s).This clause creates a single row for each group and this process is called aggregation. To use group by clause we have to use at least one aggregate function in Select statement. We can use group by clause without where clause. Syntax for Group By Clause
1. SELECT Col1, Col2, Aggreate_function 2. FROM Table_Name 3. WHERE Condition 4. GROUP BY Col1, Col2

Let's see how the Group By clause works. Suppose we have a table StudentMarks that contains marks in each subject of the student.
1. Create table StudentMarks 2. ( 3. st_RollNo int , 4. st_Name varchar(50), 5. st_Subject varchar(50), 6. st_Marks int 7. ) 8. --Insert data in StudentMarks table 9. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 10. values(1,'Mohan','Physics',75); 11. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 12. values(1,'Mohan','Chemistry',65); 13. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 14. values(1,'Mohan','Math',70); 15. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) values(2,'Vipul','Physics',70); 16. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 17. values(2,'Vipul','Chemistry',75); 18. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) values(2,'Vipul','Math',60); 19. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 20. values(3,'Jitendra','Physics',85); 21. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 22. values(3,'Jitendra','Chemistry',75); 23. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 24. values(3,'Jitendra','Math',60); 25. --Now see data in table 26. select * from StudentMarks

1. -- Group By clause without where condition 2. SELECT st_Name, SUM(st_Marks) AS 'Total Marks' 3. FROM StudentMarks 4. GROUP BY st_Name;

1. 2. 3. 4. 5.

-- Group By clause with where condition SELECT st_Name, SUM(st_Marks) AS 'Total Marks' FROM StudentMarks where st_Name='Mohan' GROUP BY st_Name;

1. -- Group By clause to find max marks in subject 2. SELECT st_Subject,max(st_Marks) AS 'Max Marks in Subject' 3. FROM StudentMarks 4. GROUP BY st_Subject;

Having Clause
This clause operates only on group rows of table(s) and act as a filter like as where clause. We use having clause to filter data that we get from group by clause. To use having clause we need to use group by clause first.
1. 2. 3. 4. 5. -- Having clause without where condition SELECT st_Name, SUM(st_Marks) AS 'Students Scored > 205' FROM StudentMarks GROUP BY st_Name HAVING SUM(st_Marks) > 205

1. 2. 3. 4. 5. 6.

-- Having clause with where condition SELECT st_Name, SUM(st_Marks) AS 'Students Scored > 205' FROM StudentMarks where st_RollNo between 1 and 3 GROUP BY st_Name HAVING SUM(st_Marks) > 205

Note

1. To use Group By Clause, we need to use at least one aggregate function 2. We can use Group By Clause with or without Where Clause. 3. To use Having Clause, we have to use Group By Clause since it filters data that we get from Group By Clause

CRUD Operations using Stored Procedures


In database, CRUD stands for 4 database operations: Create, Retrieve, Update and Delete. If we want to make a reliable and high performance system then these four operations must be implemented by stored procedures. Stored procedure also prevents Sql Injection attacks and reduce network traffic. For more about stored procedure refer the article Stored Procedure Plan Recompilation and Performance Tuning.

Create Operation
We can create temporary table(s) using stored procedure for intermediate data manipulation. Below code is used to remove duplicate records from tables using procedure.
1. 2. 3. 4. 5. 6. 7. 8. ( CREATE TABLE Employee_Test Emp_ID int identity, Emp_Name varchar (55) NULL, Emp_Sal decimal (10, 2) NULL, Emp_Designation varchar (20) NULL

) Go INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Amit',12000,'SE') 9. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Amit',12000,'SE') 10. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Mohan',15000,'SE' ) 11. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Mohan',15000,'SE' ) 12. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Riyaz',16000,'SE' ) 13. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Monu',27000,'SSE' ) 14. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Amit',12000,'SE') 15. GO 16. --Now see table 17. SELECT * FROM dbo.Employee_Test

1. create procedure usp_Removedup 2. as 3. begin 4. CREATE TABLE #tempEmpdata 5. ( 6. Emp_Name varchar (55) NULL, 7. Emp_Sal decimal (10, 2) NULL, 8. Emp_Designation varchar (20) NULL 9. ) 10. --Identify and save distinct data into temporary table

11. INSERT INTO #tempEmpdata SELECT DISTINCT Emp_Name,Emp_Sal, Emp_Designation FROM Employee_Test 12. --Delete original table data by using Truncate command, since it has Emp_ID as identiy col 13. TRUNCATE table Employee_Test 14. --Now insert data from temp table to original table 15. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation) SELECT Emp_Name,Emp_Sal,Emp_Designation FROM #tempEmpdata 16. --Now drop temp table 17. drop TABLE #tempEmpdata 18. end

1. --Execute above created procedure to remove duplicate records 2. exec usp_Removedup

1. --now see original table 2. Select * from Employee_Test

Insert Operation
We can insert records into the table(s) using stored procedure by passing data in input parameters. Below code is used to insert record in the table "Employee" using stored procedure
1. CREATE TABLE Employee 2. ( 3. EmpID int primary key, Name varchar(50), 4. Salary int, 5. Address varchar(100) 6. )

1. 2. 3. 4. 5.

Insert into Employee(EmpID,Name,Salary,Address) Values(1,'Mohan',16000,'Delhi') Insert into Employee(EmpID,Name,Salary,Address) Values(2,'Asif',15000,'Delhi') Insert into Employee(EmpID,Name,Salary,Address) Values(3,'Bhuvnesh',19000,'Noida') --See table SELECT * FROM Employee

1. CREATE PROCEDURE usp_InsertEmployee 2. @flag bit output,-- return 0 for fail,1 for success 3. @EmpID int, 4. @Name varchar(50), 5. @Salary int, 6. @Address varchar(100) 7. AS 8. BEGIN 9. BEGIN TRANSACTION 10. BEGIN TRY 11. Insert into Employee(EmpID,Name,Salary,Address) Values(@EmpID,@Name,@Salary,@Address) 12. set @flag=1; 13. IF @@TRANCOUNT > 0 14. BEGIN commit TRANSACTION; 15. END 16. END TRY 17. BEGIN CATCH 18. IF @@TRANCOUNT > 0 19. BEGIN rollback TRANSACTION; 20. END 21. set @flag=0; 22. END CATCH 23. END

1. 2. 3. 4. 5. 6. 7.

--Execute above created procedure to insert rows into table Declare @flag bit EXEC usp_InsertEmployee @flag output,1,'Deepak',14000,'Noida' if @flag=1 print 'Successfully inserted' else print 'There is some error'

1. 2. 3. 4. 5. 6. 7.

--Execute above created procedure to insert rows into table Declare @flag bit EXEC usp_InsertEmployee @flag output,4,'Deepak',14000,'Noida' if @flag=1 print 'Successfully inserted' else print 'There is some error'

1. --now see modified table 2. Select * from Employee

Retrieve Operation
We can retrieve data from one or more tables/views with the help of join, using stored procedure. We can put multiple sql statements with in a single stored procedure. Below code is used to fetch data from a table "Employee" using stored procedure
1. -- first we Insert data in the table 2. Insert into Employee(EmpID,Name,Salary,Address) Values(1,'Mohan',16000,'Delhi') 3. Insert into Employee(EmpID,Name,Salary,Address) Values(2,'Asif',15000,'Delhi') 4. Insert into Employee(EmpID,Name,Salary,Address) Values(3,'Bhuvnesh',19000,'Noida') 5. go 6. --Now we create a procedure to fetch data 7. CREATE PROCEDURE usp_SelectEmployee 8. As 9. Select * from Employee ORDER By EmpID

1. --Execute above created procedure to fetch data 2. exec usp_SelectEmployee

Update Operation
We can update records of the table(s) using stored procedure by passing data in input parameters. Below code is used to update a table "Employee" using stored procedure
1. CREATE PROCEDURE usp_UpdateEmployee 2. @flag bit output,-- return 0 for fail,1 for success 3. @EmpID int, 4. @Salary int, 5. @Address varchar(100) 6. AS 7. BEGIN 8. BEGIN TRANSACTION 9. BEGIN TRY 10. Update Employee set Salary=@Salary, Address=@Address 11. Where EmpID=@EmpID 12. set @flag=1; 13. IF @@TRANCOUNT > 0 14. BEGIN commit TRANSACTION; 15. END 16. END TRY 17. BEGIN CATCH 18. IF @@TRANCOUNT > 0 19. BEGIN rollback TRANSACTION; 20. END 21. set @flag=0; 22. END CATCH 23. END

1. 2. 3. 4. 5. 6.

--Execute above created procedure to update table Declare @flag bit EXEC usp_UpdateEmployee @flag output,1,22000,'Noida' if @flag=1 print 'Successfully updated' else print 'There is some error'

1. --now see updated table 2. Select * from Employee

Delete Operation
We can delete records of the table(s) using stored procedure by passing data in input parameters. Below code is used to update a table "Employee" using stored procedure
1. CREATE PROCEDURE usp_DeleteEmployee 2. @flag bit output,-- return 0 for fail,1 for success 3. @EmpID int 4. AS 5. BEGIN 6. BEGIN TRANSACTION 7. BEGIN TRY 8. Delete from Employee Where EmpID=@EmpID set @flag=1; 9. IF @@TRANCOUNT > 0 10. BEGIN commit TRANSACTION; 11. END 12. END TRY 13. BEGIN CATCH 14. IF @@TRANCOUNT > 0 15. BEGIN rollback TRANSACTION; 16. END 17. set @flag=0; 18. END CATCH 19. END

1. 2. 3. 4. 5. 6. 7.

--Execute above created procedure to delete rows from table Declare @flag bit EXEC usp_DeleteEmployee @flag output, 4 if @flag=1 print 'Successfully deleted' else print 'There is some error'

1. --now see modified table 2. Select * from Employee

Note

1. In stored procedure we use output parameter to return multiple values. 2. Generally we use output parameter in stored procedure to get status of the operation as I used above "@flag" output parameter to get operations status whether these are successfully executed or not.

Different Types of SQL Server Stored Procedures


A stored procedure is a precompiled set of one or more SQL statements that is stored on Sql Server. Benifit of Stored Procedures is that they are executed on the server side and perform a set of actions, before returning the results to the client side. This allows a set of actions to be executed with minimum time and also reduce the network traffic. Hence stored procedure improve performance to execute sql statements. For more about stored procedure refer the article CRUD Operations using Stored Procedures. Stored procedure can accepts input and output parameters. Stored procedure can returns multiple values using output parameters. Using stored procedure, we can Select,Insert,Update,Delete data in database.

Types of Stored Procedure System Defined Stored Procedure


These stored procedure are already defined in Sql Server. These are physically stored in hidden Sql Server Resource Database and logically appear in the sys schema of each user defined and system defined database. These procedure starts with the sp_ prefix. Hence we don't use this prefix when naming user-defined procedures. Here is a list of some useful system defined procedure.
System Defined Stored Pocedure System Procedure

Description sp_rename It is used to rename an database object like stored procedure,views,table etc. sp_changeowner It is used to change the owner of an database object. sp_help It provides details on any database object. sp_helpdb It provide the details of the databases defined in the Sql Server. sp_helptext It provides the text of a stored procedure reside in Sql Server sp_depends It provide the details of all database objects that depends on the specific database object.

Extended Procedure
Extended procedures provide an interface to external programs for various maintenance activities. These extended procedures starts with the xp_ prefix and stored in Master database. Basically these are used to call programs that reside on the server automatically from a stored procedure or a trigger run by the server. Example Below statements are used to log an event in the NT event log of the server without raising any error on the client application.
declare @logmsg varchar(100) set @logmsg = suser_sname() + ': Tried to access the dotnet system.' exec xp_logevent 50005, @logmsg print @logmsg

Example The below procedure will display details about the BUILTIN\Administrators Windows group.
EXEC xp_logininfo 'BUILTIN\Administrators'

User Defined Stored Procedure


These procedures are created by user for own actions. These can be created in all system databases except the Resource database or in a user-defined database.

CLR Stored Procedure


CLR stored procedure are special type of procedure that are based on the CLR (Common Language Runtime) in .net framework. CLR integration of procedure was introduced with SQL Server 2008 and allow for procedure to be coded in one of .NET languages like C#, Visual Basic and F#. I will discuss CLR stored procedure later.
Note

1. We can nest stored procedures and managed code references in Sql Server up to 32 levels only. This is also applicable for function, trigger and view. 2. The current nesting level of a stored procedures execution is stored in the @@NESTLEVEL function. 3. In Sql Server stored procedure nesting limit is up to 32 levels, but there is no limit on the number of stored procedures that can be invoked with in a stored procedure

SQL Server Exceptions Working


SQL Server has an exception model to handle exceptions and errors that occurs in T-SQL statements. Exception handling in Sql Server is like as exception handling in other programming language. To understand exception handling, first we need to know how many types of exception we have in Sql Server.

Types of Exceptions Statement-Level Exception


This type of exception aborts only the current running statement within a batch of T-SQL statements. The rest of the T-SQL statements will execute successfully if they have no exceptions. Let us see the below example.
--Batch SELECT POWER(4, 28) PRINT 'This statement will execute' GO

Batch-Level Exception
This type of exception aborts only the batch in which exception occurs. The rest of the batches will execute successfully if they have no exceptions. The statement in which exception occurs will be aborted and the remaining T-SQL statements within the batch will also stopped.
--First Batch DECLARE @var DECIMAL; set @var= CONVERT(DECIMAL, PRINT @var PRINT 'This statement will GO --Second Batch DECLARE @var DECIMAL; set @var= CONVERT(DECIMAL, PRINT @var PRINT 'This statement will GO

'xyz') not execute'

'12.35') execute'

Parsing and Scope-Resolution Exception


This types of exception occurs during the parsing and during the scope-resolution phase of compilation. This exception appears to behave just like batch-level exceptions. However, this has a little different behavior. If the exception occurs in the same scope of the batch, it behaves just like a batch-level exception.If the exception occurs in a lower level of scope of the batch, it behaves just like statement-level exception. Parsing Exception
--Parsing Error SELECTEmpID,Name FROM Employee PRINT 'This statement will execute' GO

--For Successfully execution we need to executed select statement as dynamic SQL using the EXEC function

EXEC('SELECTEmpID,Name FROM Employee') PRINT 'This statement will execute' GO

Scope Resolution Exception


--First Create a procedure CREATE PROCEDURE usp_print AS BEGIN Select * from tbl END GO

--Now execute above created procedure in batch EXEC usp_print PRINT 'This statement will execute' GO --Since the stored procedure creates a new scope. Hence rest statement will be executed

SQL Server Exception Handling by TRY CATCH


Like C#, SQL Server also has an exception model to handle exceptions and errors that occurs in T-SQL statements. To handle exception in Sql Server we have TRY..CATCH blocks. We put TSQL statements in TRY block and to handle exception we write code in CATCH block. If there is an error in code within TRY block then the control will automatically jump to the corresponding CATCH blocks. In Sql Server, against a Try block we can have only one CATCH block. TRY..CATCH Syntax

1. 2. 3. 4. 5. 6. 7. 8.

BEGIN TRY --T-SQL statements --or T-SQL statement blocks END TRY BEGIN CATCH --T-SQL statements --or T-SQL statement blocks END CATCH

Error Functions used within CATCH block ERROR_NUMBER()


This returns the error number and its value is same as for @@ERROR function.

ERROR_LINE()
This returns the line number of T-SQL statement that caused error.

ERROR_SEVERITY()
This returns the severity level of the error.

ERROR_STATE()
This returns the state number of the error.

ERROR_PROCEDURE()
This returns the name of the stored procedure or trigger where the error occurred.

ERROR_MESSAGE()
This returns the full text of error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.

Exception handling example


1. BEGIN TRY 2. DECLARE @num INT, @msg varchar(200) 3. ---- Divide by zero to generate Error 4. SET @num = 5/0 5. PRINT 'This will not execute' 6. END TRY 7. BEGIN CATCH 8. PRINT 'Error occured that is' 9. set @msg=(SELECT ERROR_MESSAGE()) 10. print @msg; 11. END CATCH

12. GO

1. 2. 3. 4. 5. 6. 7. 8.

BEGIN TRY DECLARE @num INT ---- Divide by zero to generate Error SET @num = 5/0 PRINT 'This will not execute' END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage; 9. END CATCH; 10. GO

Note

1. A TRY..CATCH block combination catches all the errors that have a severity between 11 and 19. 2. The CATCH block is executed only if there is an error occurs in T-SQL statements within TRY block otherwise the CATCH block is ignored. 3. Each TRY block is associated with only one CATCH block and vice versa 4. TRY and CATCH blocks cant be separated with the GO statement. We need to put both TRY and CATCH blocks within the same batch. 5. TRY..CATCH blocks can be used with transactions. We check the number of open transactions by using @@TRANCOUNT function in Sql Server. 6. XACT_STATE function within the TRY..CATCH block can be used to check whether a open transaction is committed or not. It will return -1 if transaction is not committed else returns 1.

Different Types of SQL Server Views


View is a database object. Basically it is like a virtual table that can be make on one or more database tables. Generally we put those columns in view that we need to retrieve/query again and again. Once you have created the view, you can query view like as table. We can make index, trigger on view. In Sql Server we make views for security purpose since it restricts the user to view some columns/fields of the table(s). Views show only those columns that are present in the query

which is used to make view.One more advantage of Views is, data abstraction since the end user is not aware of all the data present in database table. Syntax for View
1. CREATE VIEW view_name 2. AS 3. select_statement[]

Types of Views
In Sql Server we have two types of views.

System Defined Views


System defined Views are predefined Views that already exist in the Master database of Sql Server. These are also used as template Views for all newly created databases. These system Views will be automatically attached to any user defined database.

We have following types of system defined views.

Information Schema View


In Sql Server we have twenty different schema views. These are used to display information of a database, like as tables and columns. This type of view starts with INFORMATION_SCHEMA and after this view name.
1. --Create a table 2. create table Employee_Test 3. ( 4. Emp_ID int identity, 5. Emp_Name varchar(55), 6. Emp_Technology varchar(55), 7. Emp_Sal decimal (10,2), 8. Emp_Designation varchar(20) 9. )

10.

--To view detailed information of the columns of table Employee_Test 11. SELECT * FROM INFORMATION_SCHEMA.COLUMNS 12. where TABLE_NAME='Employee_Test'

Catalog View
Catalog Views were introduced with SQL Server 2005. These are used to show database self describing information.
13. select * from sys.tables

Dynamic Management View


Dynamic Management Views were introduced in SQL Server 2005. These Views give the administrator information of the database about the current state of the SQL Server machine. These values help the administrator to analyze problems and tune the server for optimal performance. These are of two types

Server-scoped Dynamic Management View


These are stored only in the Master database.

Database-scoped Dynamic Management View


These are stored in each database.
14. 15. --To see all SQL Server connections SELECT connection_id,session_id,client_net_address,auth_scheme 16. FROM sys.dm_exec_connections

User Defined Views


These types of view are defined by users. We have two types of user defined views.

Simple View
When we create a view on a single table, it is called simple view.
17. 18. --Now Insert data to table Employee_Test Insert into Employee_Test values ('Amit','PHP',12000,'SE'); 19. Insert into Employee_Test values ('Mohan','ASP.NET',15000,'TL'); 20. Insert into Employee_Test values ('Avin','C#',14000,'SE'); 21. Insert into Employee_Test values ('Manoj','JAVA',22000,'SSE'); 22. Insert into Employee_Test values ('Riyaz','VB',18000,'TH'); 23. -- Now create view on single table Employee_Test 24. create VIEW vw_Employee_Test 25. AS 26. Select Emp_ID ,Emp_Name ,Emp_Designation 27. From Employee_Test

28. 29.

-- Query view like as table Select * from vw_Employee_Test

In simple view we can insert, update, delete data. We can only insert data in simple view if we have primary key and all not null fields in the view.
30. 31. -- Insert data to view vw_Employee_Test insert into vw_Employee_Test(Emp_Name, Emp_Designation) values ('Shailu','SSE') 32. -- Now see the affected view 33. Select * from vw_Employee_Test

34. 35.

-- Update data to view vw_Employee_Test Update vw_Employee_Test set Emp_Name = 'Pawan' where Emp_ID = 6 36. -- Now see the affected view 37. Select * from vw_Employee_Test

38. 39. 40. 41.

-- Delete data from view vw_Employee_Test delete from vw_Employee_Test where Emp_ID = 6 -- Now see the affected view Select * from vw_Employee_Test

Complex View
When we create a view on more than one table, it is called complex view.
42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. --Create another table create table Personal_Info ( Emp_Name varchar(55), FName varchar(55), DOB varchar(55), Address varchar(55), Mobile int, State varchar(55) ) -- Now Insert data Insert into Personal_Info values ('G.Chaudary','22-101985','Ghaziabad',96548922,'UP'); 54. Insert into Personal_Info values ('B.S.Chauhan','02-071986','Haridwar',96548200,'UK'); 55. Insert into Personal_Info values ('A.Panwar','30-041987','Noida',97437821,'UP'); 56. Insert into Personal_Info values ('H.C.Patak','20-071986','Rampur',80109747,'UP'); 57. Insert into Personal_Info values ('M.Shekh','21-101985','Delhi',96547954,'Delhi'); 58. -- Now create view on two tables Employee_Test and Personal_Info 59. Create VIEW vw_Employee_Personal_Info 60. As 61. Select e.Emp_ID, e.Emp_Name,e.Emp_Designation,p.DOB,p.Mobile 62. From Employee_Test e INNER JOIN Personal_Info p 63. On e.Emp_Name = p. Emp_Name

64. 65.

-- Now Query view like as table Select * from vw_Employee_Personal_Info

We can only update data in complex view.We can't insert,update data in complex view.

66. 67.

--Update view update vw_Employee_Personal_Info set Emp_Designation = 'SSE' where Emp_ID = 3 68. -- See affected view 69. Select * from vw_Employee_Personal_Info

Note

1. We make views for security purpose since it restricts the user to view some columns/fields of the table(s). 2. One more advantage of Views is, data abstraction since the end user is not aware of all the data present in database table

Different Types of SQL Joins


Sql joins are used to fetch/retrieve data from two or more data tables, based on a join condition. A join condition is a relationship among some columns in the data tables that take part in Sql join. Basically data tables are related to each other with keys. We use these keys relationship in sql joins. Also, refer the article Different Types of LINQ Joins.

Types of Joins
In Sql Server we have only three types of joins. Using these joins we fetch the data from multiple tables based on condition.

Inner Join
Inner join returns only those records/rows that match/exists in both the tables. Syntax for Inner Join is as
1. Select * from table_1 as t1 2. inner join table_2 as t2 3. on t1.IDcol=t2.IDcol

Outer Join
We have three types of Outer Join.

Left Outer Join


Left outer join returns all records/rows from left table and from right table returns only matched records. If there are no columns matching in the right table, it returns NULL values. Syntax for Left outer Join is as :
1. Select * from table_1 as t1 2. left outer join table_2 as t2 3. on t1.IDcol=t2.IDcol

Right Outer Join


Right outer join returns all records/rows from right table and from left table returns only matched records. If there are no columns matching in the left table, it returns NULL values. Syntax for right outer Join is as :
4. Select * from table_1 as t1 5. right outer join table_2 as t2 6. on t1.IDcol=t2.IDcol

Full Outer Join


Full outer join combines left outer join and right outer join. This join returns all records/rows from both the tables.If there are no columns matching in the both tables, it returns NULL values. Syntax for full outer Join is as :

Cross Join

7. Select * from table_1 as t1 8. full outer join table_2 as t2 9. on t1.IDcol=t2.IDcol

Cross join is a cartesian join means cartesian product of both the tables. This join does not need any condition to join two tables. This join returns records/rows that are multiplication of record number from both the tables means each row on left table will related to each row of right table. Syntax for right outer Join is as :
4. Select * from table_1 5. cross join table_2

Self Join
Self join is used to join a database table to itself, particularly when the table has a Foreign key that references its own Primary Key. Basically we have only three types of joins : Inner join, Outer join and Cross join. We use any of these three JOINS to join a table to itself. Hence Self join is not a type of Sql join.

Join Examples
Suppose we following three tables and data in these three tables is shown in figure. You can download the SQL script used in this article by using link.

Inner Join
1. SELECT t1.OrderID, t0.ProductID, t0.Name, t0.UnitPrice, t1.Quantity, t1.Price 2. FROM tblProduct AS t0 3. INNER JOIN tblOrder AS t1 ON t0.ProductID = t1.ProductID 4. ORDER BY t1.OrderID

Inner Join among more than two tables


1. 2. 3. 4. 5. SELECT t1.OrderID, t0.ProductID, t0.Name, t0.UnitPrice, t1.Quantity, t1.Price, t2.Name AS Customer FROM tblProduct AS t0 INNER JOIN tblOrder AS t1 ON t0.ProductID = t1.ProductID INNER JOIN tblCustomer AS t2 ON t1.CustomerID = t2.CustID ORDER BY t1.OrderID

Inner Join on multiple conditions


1. 2. 3. 4. 5. SELECT t1.OrderID, t0.ProductID, t0.Name, t0.UnitPrice, t1.Quantity, t1.Price, t2.Name AS Customer FROM tblProduct AS t0 INNER JOIN tblOrder AS t1 ON t0.ProductID = t1.ProductID INNER JOIN tblCustomer AS t2 ON t1.CustomerID = t2.CustID AND t1.ContactNo = t2.ContactNo ORDER BY t1.OrderID

Left Outer Join


1. SELECT t1.OrderID AS OrderID , t0.ProductID , t0.Name , t0.UnitPrice , t1.Quantity AS Quantity , t1.Price AS Price 2. FROM tblProduct AS t0 3. LEFT OUTER JOIN tblOrder AS t1 ON t0.ProductID = t1.ProductID 4. ORDER BY t0.ProductID 5.

Right Outer Join


1. SELECT t1.OrderID AS OrderID , t0.ProductID , t0.Name , t0.UnitPrice , t1.Quantity AS Quantity , t1.Price AS Price 2. FROM tblProduct AS t0 3. RIGHT OUTER JOIN tblOrder AS t1 ON t0.ProductID = t1.ProductID 4. ORDER BY t0.ProductID

Full Outer Join


1. SELECT t1.OrderID AS OrderID , t0.ProductID , t0.Name , t0.UnitPrice , t1.Quantity AS Quantity , t1.Price AS Price 2. FROM tblProduct AS t0 3. FULL OUTER JOIN tblOrder AS t1 ON t0.ProductID = t1.ProductID 4. ORDER BY t0.ProductID

Cross Join
1. SELECT t1.OrderID, t0.ProductID, t0.Name, t0.UnitPrice, t1.Quantity, t1.Price 2. FROM tblProduct AS t0, tblOrder AS t1 3. ORDER BY t0.ProductID

Self Join
To understand Self Join, suppose we following two tables and data in these two tables is shown in figure.
1. 2. 3. 4. 5. 6. CREATE TABLE emp ( id int NOT NULL primary key, name varchar(100) NULL, designation varchar(50) NULL, supid int foreign key references emp(id) ) -- In this table we have a Foreign key supid that references its own Primary Key id. We use it for Self Join 7. INSERT INTO emp(id,name,designation) VALUES(1,'mohan','Manger') 8. INSERT INTO emp(id,name,designation,supid) VALUES(2,'raj kumar','SE',1) 9. INSERT INTO emp(id,name,designation) VALUES(3,'bipul kumar','Manager') 10. INSERT INTO emp(id,name,designation,supid) VALUES(4,'mrinal kumar','SE',2) 11. INSERT INTO emp(id,name,designation,supid) VALUES(5,'jitendra kumar','SE',2)

1. CREATE TABLE empinfo 2. ( 3. id int primary key, 4. address varchar(50) NULL 5. ) 6. INSERT INTO empinfo(id,address) VALUES(1,'Delhi') 7. INSERT INTO empinfo(id,address) VALUES(2,'Noida') 8. INSERT INTO empinfo(id,address) VALUES(4,'Gurgaon') 9. INSERT INTO empinfo(id,address) VALUES(6,'Delhi') 10. INSERT INTO empinfo(id,address) VALUES(7,'Noida')

1.

select e.id,e.name,e.supid as managerid, ei.name as managername from emp e left join emp ei on e.supid=ei.id; 2. -- outer keyword is optional

SQL Integrity Constraints or Constraints


Constraints are some rules that enforce on the data to be enter into the database table. Basically constraints are used to restrict the type of data that can insert into a database table.Constraints can be defined in two ways:

Column Level
The constraints can be specified immediately after the column definition with the CREATE TABLE statement. This is called column-level constraints.

Table Level
The constraints can be specified after all the columns are defined with the ALTER TABLE statement. This is called table-level constraints.

Types of SQL Constraints


In Microsoft SQL Server we have six types of constraints

Primary Key Constraints


Primary key is a set of one or more fields/columns of a table that uniquely identify each record/row in database table. It can not accept null, duplicate values. Primary key constraint at column level
CREATE TABLE table_name ( col1 datatype [CONSTRAINT constraint_name] PRIMARY KEY, col2 datatype );

Primary key constraint at table level


ALTER TABLE table_name ADD[CONSTRAINT constraint_name] PRIMARY KEY (col1,col2)

Unique Key Constraints


Unique key is a set of one or more fields/columns of a table that uniquely identify each record/row in database table.It is like Primary key but it can accept only one null value and it can not have duplicate values Unique key constraint at column level
CREATE TABLE table_name ( col1 datatype [CONSTRAINT constraint_name] UNIQUE, col2 datatype );

Unique key constraint at table level


ALTER TABLE table_name ADD[CONSTRAINT constraint_name] UNIQUE (col1,col2)

Foreign Key Constraints


Foreign Key is a field in database table that is Primary key in another table. It can accept multiple null, duplicate values. Foreign key constraint at column level
CREATE TABLE table_name ( col1 datatype [CONSTRAINT constraint_name] REFERENCES referenced_table_name(referenced_table_column_name), col2 datatype );

Foreign key constraint at table level


ALTER TABLE table_name ADD[CONSTRAINT constraint_name] REFERENCES referenced_table_name(referenced_table_col)

Not Null Constraints


This constraint ensures that all rows in the database table must contain value for the column which is specified as not null means a null value is not allowed in that column.

Not Null constraint at column level


CREATE TABLE table_name ( col1 datatype [CONSTRAINT constraint_name] NOT NULL, col2 datatype );

Not Null constraint at table level


ALTER TABLE table_name ALTER COLUMN col1 datatype NOT NULL

Check Constraints
This constraint defines a business rule on a column in the database table that each row of the table must follow this rule. Check constraint at column level
CREATE TABLE table_name ( col1 datatype [CONSTRAINT constraint_name] CHECK (condition), col2 datatype );

Check constraint at table level


ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK(condition)

Different Types of SQL Keys


A key is a single or combination of multiple fields in a table. Its is used to fetch or retrieve records/data-rows from data table according to the condition/requirement. Keys are also used to create relationship among different database tables or views.

Types of SQL Keys


We have following types of keys in SQL which are used to fetch records from tables and to make relationship among tables or views.

Super Key
Super key is a set of one or more than one keys that can be used to identify a record uniquely in a table.Example : Primary key, Unique key, Alternate key are subset of Super Keys.

Candidate Key
A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table. There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key. Example: In below diagram ID, RollNo and EnrollNo are Candidate Keys since all these three fields can be work as Primary Key.

Primary Key
Primary key is a set of one or more fields/columns of a table that uniquely identify a record in database table. It can not accept null, duplicate values. Only one Candidate Key can be Primary Key.

Alternate key
A Alternate key is a key that can be work as a primary key. Basically it is a candidate key that currently is not primary key. Example: In below diagram RollNo and EnrollNo becomes Alternate Keys when we define ID as Primary Key.

Composite/Compound Key
Composite Key is a combination of more than one fields/columns of a table. It can be a Candidate key, Primary key.

Unique Key
Uniquekey is a set of one or more fields/columns of a table that uniquely identify a record in database table. It is like Primary key but it can accept only one null value and it can not have duplicate values. For more help refer the article Difference between primary key and unique key.

Foreign Key
Foreign Key is a field in database table that is Primary key in another table. It can accept multiple null, duplicate values. For more help refer the article Difference between primary key and foreign key. Example : We can have a DeptID column in the Employee table which is pointing to DeptID column in a department table where it a primary key. Defined Keys -

1. CREATE TABLE Department 2. ( 3. ID int PRIMARY KEY, 4. Name varchar (50) NOT NULL, 5. Address varchar (200) NOT NULL, ) 6. CREATE TABLE Student 7. ( 8. ID int PRIMARY KEY, 9. RollNo varchar(10) NOT NULL, 10. Name varchar(50) NOT NULL, 11. EnrollNo varchar(50) UNIQUE, 12. Address varchar(200) NOT NULL, 13. DeptID int FOREIGN KEY REFERENCES Department(DeptID) 14. )

Note

1. Practically in database, we have only three types of keys Primary Key, Unique Key and Foreign Key. Other types of keys are only concepts of RDBMS that we need to know.

Basics of SQL Commands


SQL commands are a set of instructions that are used to interact with the database like Sql Server, MySql, Oracle etc. SQL commands are responsible to create and to do all the manipulation on the database. These are also responsible to give/take out access rights on a particular database

Sql Commands Category


We have different sql commands for different-different purpose. We can grouped Sql Commands into five major categories depending on their functionality.

Data Definition Language (DDL)

These SQL commands are used to create, modify, and drop the structure of database objects like table, view, procedure, indexes etc. In this category we have CREATE, ALTER, DROP and TRUNCATE commands.
Note

1. Only with DDL commands we need to write keyword (like table, procedure, view, index, function) with the syntax of command. 2. These commands are used to create/modify the structure of the database object.
Example
3. 4. 5. 6. 7. 8. CREATE TABLE TABLE_NAME ( COL1 VARCHAR(10), COL2 VARCHAR(20), ); --Here "TABLE" is a keyword that is used to create table "TABLE_NAME" 9. CREATE VIEW VIEW_NAME 10. AS 11. BEGIN 12. SELECT * FROM EMP_TABLE 13. END 14. --Here "VIEW" is a keyword that is used to create VIEW "VIEW_NAME"

Data Manipulation Language (DML)


These SQL commands are used to store, modify, and delete data from database tables. In this category we have INSERT, UPDATE, and DELETE commands.

Data Query Language (DQL)


These SQL commands are used to fetch/retrieve data from database tables. In this category we have only SEELCT command.

Transaction Control Language (TCL)


These SQL commands are used to handle changes which affect the data in database. Basically we use these commands with in the transaction or to make a stable point during changes in database at which we can rollback the database state if required. In this category we have SAVEPOINT, ROLLBACK and COMMIT commands.

Data Control Language (DCL)


These SQL commands are used to implement security on database objects like table,view,stored procedure etc. In this category we have GRANT and REVOKE commands.

Note

15. Grant Command : This command is used to give permission to specific users on specific database objects like table, view etc. 16. Revoke Command : This command is used to take out permission from specific users on specific database objects like table, view etc.

Introduction to SQL Server


Microsoft SQL Server is a Relational Database Management System(RDBMS) developed by Microsoft. It is designed to run on a central server, so that multiple users can access the same data simultaneously. Generally users access the database through an application.
SQL Server Release History Version Year Release Name 1.0 for OS/2 1989 SQL Server 1.0(16bit) 1.1 for OS/2 1991 SQL Server 1.1(16bit) 4.21 for WinNT 1993 SQL Server 4.21 6.0 1995 SQL Server 6.0 6.5 1996 SQL Server 6.4 7.0 1998 SQL Server 7.0 8.0 2000 SQL Server 2000 8.0 2003 SQL Server 2000 (64-bit) 9.0 2005

SQL Server 2005 10.0 2008 SQL Server 2008 10.5 2010 SQL Server 2008 R2

Sql Server Components Protocol Layer


Protocol layer implements the external interface to SQL Server. TDS is an application layer protocol, that is used to transfer data between a database server and a client.

Data Storage
The main unit of data storage is a database, which is a collection of data. The data in the SQL Server database is stored in primary data files with an extension .mdf and Secondary data files, with an extension .ndf extension are used to store optional metadata. Log files in SQL Server are recognized with the .ldf extension.

Buffer Management
SQL Server buffers pages in RAM to minimize disc Input/Output. A 8 KB page could be buffered in-memory and the set of all pages currently buffered is called the buffer cache. On the basis of available memory, SQL Server decides how many pages will be cached in memory. The buffer cache is managed by the Buffer Manager.

Logging and Transaction


SQL Server uses transaction to make sure that any operation either totally completes or is undone if fails, but never leaves the database in an intermediate state. Any changes made to a page will update the in-memory cache of the page and simultaneously all the operations performed will be written to a log, along with the transaction ID. Each log entry is recognized by an increasing Log Sequence Number (LSN) which makes sure that no event overwrites another event. SQL Server makes sure that the log will be written onto the disc before the actual page is written back.

Concurrency and locking


when multiple users update the same data, or attempt to read data that is in the process of being changed by another user. In SQL Server we have two modes of concurrency control - pessimistic concurrency and optimistic concurrency. In pessimistic concurrency control, SQL Server controls concurrent access by using locks (shared or exclusive).

In Optimistic concurrency control, a new version of a row is created whenever the row is updated. Both the versions of the row are stored and maintained into a system defined database Tempdb.

Data Retrieval
Data retrieval from SQL Server is done using T-SQL. SQL Server also allows us to write stored procedures to query the data.

SQL CLR (Common Language Runtime)


SQL Server 2005 also has a new component named SQL CLR via which it integrates with .NET Framework. When we write code for SQL CLR, data stored in SQL Server databases can be accessed by using the ADO.NET APIs like any other application that accesses SQL Server data.

Ado.Net Tutorial - Getting Started with Ado.Net

DB2 Connection Strings in Ado.Net


DB2 database is most useful RDBMS developed by IBM. Basically it is not easy to remember different database connection strings in Ado.Net. In Ado.net to make connection to DB2 we have multiple options. We have different connection string to connect to the DB2 database. So I am sharing some connection strings to connect to the DB2 database using different drivers.

Using ODBC
// ODBC without DSN using System.Data.Odbc; OdbcConnection conn = new OdbcConnection(); conn.ConnectionString = "Driver={IBM DB2 ODBC DRIVER};DataBase=DataBaseName; HostName=ServerName; Protocol=TCPIP;Port=PortNumber;Uid=UserName;Pwd=Secret"; conn.Open();

Using OLEDB
// OleDb -- Microsoft Driver using System.Data.OleDb; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = "Driver=DB2OLEDB; Network Transport Library=TCPIP; Network Address=xxx.xxx.xxx.xxx; Package Collection=CollectionName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;"; conn.Open(); // OleDb -- IBM Driver

using System.Data.OleDb; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = "Driver=IBMDADB2; DataBase=DataBaseName; HostName=ServerName; Protocol=TCPIP; Port=PortNumber; Uid=UserName; Pwd=Secret;"; conn.Open();

Using .Net DataProvider


// .NET DataProvider from IBM using IBM.Data.DB2; Db2Connection conn = new Db2Connection(); conn.ConnectionString = "DataBase=DataBaseName;Uid=UserName;Pwd=Secret"; conn.Open();

MySql Connection Strings in Ado.Net


Today, MySql is open source database in the world. In Ado.net to make connection to MySql , we have different connection strings. Basically it is not easy to remember different database connection strings in Ado.Net. So I am sharing some connection strings to connect to the MySql database using different drivers.

Using ODBC
// ODBC -- MyODBC Driver -- remote database using System.Data.Odbc; OdbcConnection conn = new OdbcConnection(); conn.ConnectionString = "Driver={MySql}; Server=db.domain.com; Option=131072; Port=3306; Stmt=; DataBase=DataBaseName; Uid=UserName; Pwd=Secret;" ; conn.Open();

Using OLEDB
// OleDb using System.Data.OleDb; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = "Provider=MySqlProv; Data Source=ServerName; User id=UserName; Password=Secret"; conn.Open();

Using .Net DataProvider


// .NET DataProvider from CoreLab using CoreLab.MySql; MySqlConnection conn = new MySqlConnection(); conn.ConnectionString ="Host=ServerName; DataBase=DataBaseName; Protocol=TCP; Port=3306; Direct=true; Compress=false; Pooling=true; Min Pool Size=0; Max Pool Size=100; Connection Lifetime=0; User id=UserName;Password=Secret"; conn.Open();

Oracle Connection Strings in Ado.Net

Oracle is most used database in the world. In Ado.net to make connection to Oracle we have multiple options. For this purpose we have different connection string to connect to the Oracle. Basically it is not easy to remember different database connection strings in Ado.Net. So I am sharing some connection strings to connect to the Oracle database using different drivers.

Using ODBC
1. // ODBC -- New Microsoft Driver 2. using System.Data.Odbc; 3. OdbcConnection conn = new OdbcConnection(); 4. conn.ConnectionString = "Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=UserName;Pwd=Secret;"; 5. conn.Open(); 6. // ODBC -- Oracle Driver 7. using System.Data.Odbc; 8. OdbcConnection conn = new OdbcConnection(); 9. conn.ConnectionString = "Driver={Oracle ODBC Driver};Dbq=myDataBase;Uid=UserName;Pwd=Secret;"; 10. conn.Open();

Using OLEDB
1. // OleDb -- Oracle Driver -- Standard Connection 2. using System.Data.OleDb; 3. OleDbConnection conn = new OleDbConnection(); 4. conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;User id=UserName;Password=Secret;"; 5. conn.Open(); 6. // OleDb -- Oracle Driver -- Trusted Connection 7. using System.Data.OleDb; 8. OleDbConnection conn = new OleDbConnection(); 9. conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;OSAuthent=1;"; 10. conn.Open(); 11. // or 12. using System.Data.OleDb; 13. OleDbConnection conn = new OleDbConnection(); 14. conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;User id=admin;Password=pwd"; 15. conn.Open();

Microsoft Access Connection Strings


In Ado.net we have multiple options to connect to Microsoft Access database. For this purpose we have different connection string to connect to the Microsoft Access database. Basically it is not easy to remember different database connection strings in Ado.Net. So I am sharing some connection strings to connect to the Microsoft Access database using different drivers.

Using ODBC
// ODBC -- Standard Security using System.Data.Odbc; OdbcConnection conn = new OdbcConnection(); conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; Dbq=c:\myPath\myDb.mdb; Uid=Admin; Pwd=;password"; conn.Open(); // ODBC -- Workgroup (System Database) using System.Data.Odbc; OdbcConnection conn = new OdbcConnection(); conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; Dbq=c:\myPath\myDb.mdb; SystemDb=c:\myPath\myDb.mdw;"; conn.Open();

Using OLEDB
// OleDb with MS Jet -- Standard Security using System.Data.OleDb; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\mypath\myDb.mdb; User id=admin;Password=password"; conn.Open(); // OleDb with MS Jet -- Workgroup (System Database) using System.Data.OleDb; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\mypath\myDb.mdb; System Database=c:\mypath\myDb.mdw"; conn.Open();

Microsoft SQL Server Connection Strings


Sql Server database is more compatible database with Ado.Net. Since Sql Server and Ado.Net, both are the product of Microsoft. Basically it is not easy to remember different database connection strings in Ado.Net. In Ado.net to make connection to Sql Server we have multiple options. We have different connection string to connect to the Sql Server database. So I am sharing some connection strings to connect to the Sql Server database using different drivers.

Using ODBC
1. // ODBC -- Standard Connection 2. using System.Data.Odbc; 3. OdbcConnection conn = new OdbcConnection(); 4. conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Uid=UserName; Pwd=Secret"; 5. conn.Open(); 6. // ODBC -- Trusted Connection 7. using System.Data.Odbc; 8. OdbcConnection conn = new OdbcConnection(); 9. conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Uid=admin; Pwd=password"; 10. conn.Open(); 11. // or 12. OdbcConnection conn = new OdbcConnection();

13. conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Trusted_Connection=Yes;"; 14. conn.Open();

Using OLEDB
1. // OleDb -- Standard Connection 2. using System.Data.OleDb; 3. OleDbConnection conn = new OleDbConnection(); 4. conn.ConnectionString = "Driver=SQLOLEDB; Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;"; 5. conn.Open(); 6. // OleDb -- Trusted Connection 7. using System.Data.OleDb; 8. OleDbConnection conn = new OleDbConnection(); 9. conn.ConnectionString = "Driver=SQLOLEDB; Data Source=ServerName; Initial Catalog=DataBaseName; Integrated Security=SSPI;"; 10. conn.Open();

Using .Net DataProvider


1. // .NET DataProvider -- Standard Connection 2. using System.Data.SqlClient; 3. SqlConnection conn = new SqlDbConnection(); 4. conn.ConnectionString ="Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;"; 5. conn.Open(); 6. // .NET DataProvider -- Trusted Connection 7. using System.Data.SqlClient; 8. SqlConnection conn = new SqlConnection(); 9. conn.ConnectionString = "Data Source=ServerName; Initial Catalog=DataBaseName; Integrated Security=SSPI;"; 10. conn.Open();

Introduction to Ado.net
Before Ado.net we use Ado (Active Database Object) to access data from databae. Basically Ado has automatic driver detection technique and tt has only one drawback that it only provide a connected environment so efficiency of system may decrease. ADO.NET is a new database technology used by .Net platform (introduced in 2002).Infact it is a set of classes used to communicate between an application front end and a database.It supports both connected & disconnection mode of data access.

Mandatory Namespaces used in ADO.Net


In any .NET data access page, before you connect to a database, you first have to import all the necessary namespaces that will allow you to work with the objects required. Namespaces used in ADO.Net are :

System.Data
It contains the common classes for connecting, fetching data from database. Classes are like as DataTable, DataSet, DataView etc.

System.Data.SqlClient
It contains classes for connecting, fetching data from Sql Server database. Classes are like as SqlDataAdapter,SqlDataReader etc.

System.Data.OracleClient
It contains classes for connecting, fetching data from Oracle database. Classes are like as OracleDataAdapter,OracleDataReader etc.

System.Data.OleDb
It contains classes for connecting, fetching data from any database(like msaccess, db2, oracle, sqlserver, mysql). Classes are like as OleDbDataAdapter,OleDbDataReader etc.

System.Data.Odbc
It contains classes for connecting, fetching data from any database(like msaccess, db2, oracle, sqlserver, mysql). Classes are like as OdbcDataAdapter,OdbcDataReader etc.

Component of ADO.NET architecture Data Provider


Data provider is a set of ADO.Net classes that allow us to access a database. Basically, it is a bridge between our application (We can say front-end) and data source. There are following Data Provider : 1. SqlServer Data Provider:-It is used to access data from SqlServer database (for version 7.0 or later). 2. Oracle Data Provider:-It is used to access data from oracle database (for version 8i or later). 3. OleDb Data Provider:-It is used to access data from any database (msaccess, mysql, db2).

4. Odbc Data Provider :-It is used to access data from any database (msaccess, mysql, db2).

Data Set
Basically it is a small Data structure that may contain multiple datatables from multiple sources.The information in dataset is created inform of XML and is stored with .xsd extention.It support disconnected mode of data access.It has both scrolling mode means forward and backward scrolling mode (fetching of data).DataSet can have multiple Datatable from multiple sources but DataReader is able toread only single Datatable.

.Net Framework Tutorial - Getting Started with .Net Framework

.Net Garbage Collection in depth


Memory management is the main concern for any application whether application is window based or web based. In .Net, CLR has garbage collector that executes as a part of our program and responsible for reclaiming the memory of no longer used objects. Garbage collector free the memory for objects that are no longer referenced and keeps the memory for future allocations.

Advantage of Garbage Collector


1. Allow us to develop an application without having worry to free memory. 2. Allocates memory for objects efficiently on the managed heap. 3. -Reclaims the memory for no longer used objects and keeps the free memory for future allocations. 4. Provides memory safety by making sure that an object cannot use the content of another object.

Memory Allocation in Managed Heap


The managed heap is a segment of contiguous memory to store and manage objects. The memory for newly created object is allocated at the next available location on the managed heap. If there is available free memory, the garbage collector doesn't search the dead objects for memory reclaim and memory allocations has been done very fast. If the memory is insufficient to create the object, the garbage collector search the dead objects for memory reclaim for the newly object.

An object is created using the new operator. This operator first makes sure that the bytes required by the new object fit in the reserved region (committing storage if necessary). If the object fits, NextObjPtr points to the object in the heap and object's constructor is called and the new operator returns the address of the object.

Key points about Garbage Collector


1. All objects in the heap are allocated from one contiguous range of memory address and heap is divided into generations so that it is easy to eliminate the garbage objects by looking at only a small fraction of the heap. 2. Almost, all objects with-in a generation are of the same age. 3. The newest objects are created at higher memory address while oldest memory objects are at lowest memory address with in the heap. 4. The allocation pointer for the new objects marks the boundary between the allocated and free memory. 5. Periodically the heap is compacted by removing the dead objects and sliding up the live objects towards the lower memory address end of the heap as shown in above fig. 6. The order of objects (after memory reclaims) in memory remains the same as they were created. 7. There are never any gaps among the objects in the heap.

8. Only some of the free memory is committed when required and more memory is acquired from the OS in the reserved address range.

Generations in Managed Heap


The managed heap is organized into three generations so that it can handle short lived and long lived objects efficiently. Garbage collector first reclaim the short lived objects that occupy a small part of the heap.

Generation 0
This is the youngest generation and contains the newly created objects. Generation 0 has short-lived objects and collected frequently. The objects that survive the Generation 0 are promoted to Generation 1. Example : A temporary object.

Generation 1

This generation contains the longer lived objects that are promoted from generation 0. The objects that survive the Generation 1 are promoted to Generationen 2. Basically this generation serves as a buffer between short-lived objects and longest-lived objects.

Generation 2
This generation contains the longest lived objects that are promoted from generation 1 and collected infrequently. Example : An object at application level that contains static data which is available for the duration of the process.

Garbage Collector Working Phase Marking Phase


In this phase garbage collector finds and creates a list of all live objects.

Relocating Phase
In this phase garbage collector updates the references to the objects that will be compacted.

Compacting Phase
In this phase garbage collector reclaims the memory occupied by the dead objects and compacts the surviving objects. The compacting phase moves the surviving objects toward the older end of the memory segment.

Note

1. The large object heap is not compacted, because copying large objects imposes a performance penalty.

Garbage Collection Algorithm


Garbage collector determine whether any object in the heap is dead or not being used by the application. If such objects exist then memory used by these objects can be reclaimed. But how garbage collector know about these objects? Each and every application has a set of roots and these identify the storage locations for the objects on the managed heap. Example : All the global, static objects pointers and all the local variable/ parameter object pointers on the thread's stack in the application are considered part of the appilcation's roots.

More over any CPU registers containing pointers to objects in the managed heap are also considered a part of the application's roots. The list of active roots is maintained by the JIT compiler and CLR, and is made accessible to the garbage collector's algorithm.
Memory Reclaim Process

Now the garbage collecor starts go through the roots and make a graph of all the objects reachable from the roots. The below fig. shows a heap with allocated objects. In this heap the application roots directly refer to the objects 1,3,4,6 and object 3 & 6 refers to the objects 8 & 10. Hence all these objects will bacome the part of the live objects graph.

The objects which are not reachable from application's roots, are considered as garbage since these are not accessible by the application. In above heap objects 2,5,7,9 will be considered as dead objects.

The garbage collector then remove the dead objects from the heap and live objects will move toward the older end of the memory segment as shown in below fig. Garbage collector also updates all the references(including root references) to the moving objects in the heap.

Reference : http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

.Net Garbage Collection and Finalization Queue


Finalize is a special method that is automatically called by the garbage collector (GC) before the object is collected. This method is only called by the GC. Destructor in C# are automatically translated into Finalize. You can see the IL code using IDASM where you will see that destructor is renamed to finalize.
1. public class A 2. { 3. ~A() 4. { 5. Console.WriteLine("Class A Destructor"); 6. //Clean up unmanaged resources here 7. } 8. }

The CLR translate the above C# destructor to like this:


1. public override void Finalize() 2. { 3. try 4. { 5. Console.WriteLine("Class A Destructor"); 6. //Clean up unmanaged resources here 7. } 8. finally 9. { 10. base.Finalize(); 11. } 12. }

Fundamental of Finalization
When a new object is created, the memory is allocated in the managed heap. If newly created object have a Finalize() method or a destructor then a pointer pointing to that object is put into the finalization queue. Basically, finalization queue is an internal data structure that is controlled and managed by the GC. Hence each pointer in finalization queue points to an object that have its Finalize method call before the memory is reclaimed. In the below fig. the managed heap contains 10 objects and objects 2,3,5,6,and 10 also contains the Finalize method. Hence pointers to these objects were added to the finalization queue.

When the garbage collecor starts go through the roots, it make a graph of all the objects reachable from the roots. The below fig. shows a heap with allocated objects. In this heap the application roots directly refer to the objects 1,3,4,6 and object 3 & 6 refers to the objects 8 & 10. Hence all these objects will bacome the part of the live objects graph.

The objects which are not reachable from application's roots, are considered as garbage since these are not accessible by the application. In above heap objects 2,5,7,9 will be considered as dead objects.

Before the collections for dead objects, the garbage collector looks into the finalization queue for pointers identifies these objects. If the pointer found, then the pointer is flushed from the finalization queue and append to the freachable queue .The freachable queue is also an internal data structure and controlled by the garbage collector. Now each and every pointer with in the freachable queue will identify an object that is ready to have its Finalize method called. After the collection, the managed heap looks like below Fig. Here, you see that the memory occupied by objects 7 and 9 has been reclaimed because these objects did not have a Finalize method. However, the memory occupied by objects 2 and 5 could not be reclaimed because their Finalize method has not been called yet.

When an object's pointer entry move from the finalization queue to the freachable queue, the object is not considered garbage and its memory is not reclaimed. There is a special run-time thread that is dedicated for calling Finalize methods. When there is no entry in the freachable queue then this thread sleeps. But when there is entry in the freachable queue, this thread wakes and removes each entry from the queue by calling each object's Finalize method.

The next time the garbage collector is invoked, it sees that the finalized objects are truly garbage, since the application's roots don't point to it and the freachable queue no longer points to it. Now the memory for the object is simply reclaimed.
Note

1. The two GCs are required to reclaim memory used by objects that have FInalize method. Reference : http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

Introduction to Ajax
AJAX is not a technology but it is a group of technologies (as Javascript, CSS, XHTML, DOM etc). We can also say it is a combination of client side technologies that provides asynchronous communication b\w user interface and web server so that partial page rendering occurs instead of complete page post back. It is platform independent means AJAX is a cross platform technology that can be used an any Operating system since it is based an XML & Javascript. It also supports open source implementation of other technology. It partially render the page to the server instead of complete page postback.We use AJAX for developing faster better and more interactive web applications.AJAX use HTTP request b\w web server & browser.

Ajax Features
1. 2. 3. 4. 5. Ajax minimize round trips to the server. It is language independent means we can use ajax in every language Ajax is platform independent. Rendering of webpage is faster. Reduce consumption of server resources.

Ajax Drawback
Response Time in AJAX based development we should care of response time b\w client & server because it gets normally delayed. AJAX is based on Java Script and different browser implement Javascript different way. Hence here may be a problems on different browser. Example :Uploading of file in gmail & do working in message body box.

Script Manager
It manages all ASP.Net AJAX controls on the web page. It renders the AJAX library to the browser and supports partial page rendering. It also manage partial page uploades and provide access to web service method. Without script manager we can't use AJAX controls on the web page.

Introduction to Asp.net
According to Microsoft, "ASP.NET is a technology for building powerful, dynamic Web applications and is part of the .NET Framework". Infact Asp.Net is a programming framework used to develop web applications and web services. Basically it is next version of asp. It provides the easy way to build, deploy & run web application on any browser.

Benefits of Asp.Net
1. Asp.Net makes development simple and easy to maintain with event-driven and server side programming model. 2. Asp.Net source code is executed on the server. The source code is complied first time the page is requested. The server serves the complied version of the page for use next time the page is requested. 3. Asp.Net provides validations controls. 4. The html produced by Asp.Net is sent back to the browser. The application code that we write is not sent back to the browser and is not stolen easily. 5. In Asp.Net business logic(in .cs class file) and presentation logic(in .aspx file) are in separate files.

Asp .Net Page Life Cycle Events


At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle. Asp.Net 3.5 & 4.0 page life cycle has following events in sequence :

PreInit
It is is entry point of page life cycle. It checks IsPostBack property to check or recreate dynamic controls. In this we can set master pages dynamically & set and get profile property values.

Init
It is is raised after all controls of page are initilised and skin properties are set. It is used to read or initialise control properties.

InitComplete
This indicates that page is completely initialised.

Preload
This event is called before loading the page in the RAM(memory). If any processing on a control or on page is required we use it.

Load
This invokes the onload event of the page. In this we create connection to the database, get/set controls values and get/set view state values.

loadComplete
This indicates that page is completely loaded into memory.

Prender

we use this event to make final changes to the controls or page before rendering it to the browser.

SaveStateComplete
View state of each control is saved before this event occurs. If we want to change the view state of any control then we use this event. This event can not be used to change the other properties of the controls.

Render/PrenderComplete
This indicates that page is completely rendered to the browser.Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.

Unload
The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.We can use this event for closing files & database connection. This event occurs for each control.

Asp.net Development Models


Asp.net framework is a part of .net platform for building, deploying and running web applications. Asp.net development framework is used for developing web applications and web sites with the help of Html, CSS, jQuery, JavaScript and many more javascript library like knout. There are three development models in asp.net as shown below.

Asp.Net Development Models

Asp.Net Web Form Asp.Net Web Form is a traditional event driven development model

Asp.Net Web Form has drag and drop server controls, server events and state management techniques.

Asp.Net Web Form has built-in data controls and best for rapid development with powerful data access.

Visual studio and Visual web developer(free) are tools for developing Asp.Net Web Forms.

Asp.Net MVC Asp.Net MVC is a lightweight and MVC (Model, View, Controller) pattern based development model. Asp.Net MVC divide the web application into three components : Model,View and Controller. It has no drag and drop server controls, server events and state management techniques. Asp.Net MVC is lightweight, provide full control over markup and support many features that allow fast & agile development. Henec it is best for developing interactive web application with latest web standards. Visual studio and Visual web developer(free) are tools for developing Asp.Net MVC application.

Asp.Net Web Page Asp.Net Web Page is also a lightweight and Razor syntax based development model. Asp.Net Web Page is a single page model like classic Asp and Php.It also has no drag and drop server controls, server events and state management techniques. Asp.Net Web Page has built-in template and helpers also provide full control over markup. Hence it is best for developing beautiful web application with latest web standards.

WebMatrix is a free tool for developing Asp.Net Web Page.

Introduction to Entity Framework


ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational database. It enabling developers to deal with data as objects and properties.Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects using C# or VB.Net. The Entity Frameworks ORM implementation also provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals. ADO.NET Entity Framework is targeted for developing Enterprise applications which can support MS SQL databases as well as other databases like as Oracle, DB2, MySql and many more. To learn entity framework first we need to know what is orm. I am going to give the overview of orm.

What is O/RM?
O/RM is an acronym that stands for object/relational mapping. Basically, an O/RM framework is used to persist model objects in a relational database and retrieve them. It uses metadata information to interface with the database. This way, your data-layer code knows nothing about the database structure. The O/RM tool becomes middleware that completely hides the complexity. The heart of O/RM is the mappingthe mapping technique is what binds the object and relational worlds. By mapping, you express how a class and its properties are related to one or more tables in the database. This information is used by the O/RM tools engine to dynamically build SQL code that retrieves data and transforms it into objects. Similarly, by tracking changes to objects properties, it can use mapping data to send updates back to the database. The mapping information is generally expressed as an XML file. As an alternative, some O/RM tools use attributes on the classes and their properties to maintain mapping data.

Advantage of Entity Framework Productivity


Entity Framework can take up to 35 percent of the entire application code. It make the developers life easier than ever. In spite of its limitations, the designer integrated into Visual Studio dramatically simplifies the mapping process.

Maintainability
Since you have the fewer lines of code to fetch data from database,the fewer lines of code you have to maintain. This is particularly true in the big projects.

Performance
The complexity of O/RM introduces an obvious slowdown in performance. In entity framework first request to fetch data is little bit slow but after that is fast to fetch data from database.

Entity Framework Models


Microsofts Entity Framework evolved from a methodology known as Entity Relationship Modeling (ERM). An ERM defines a schema of entities and their relationships with one another. Entities are not the same as objects. Entities define the schema of an object, but not its behavior. So, an entity is something like the schema of a table in your database, except that it describes the schema of your business objects. There are three models in the entity framework:

conceptual model

The conceptual model is where you describe the model classes. This file is split into two main sections: the first is a container that lists all the entities and the relationships that are managed by Entity Framework, and the second contains a detailed description of their structure.

STORAGE MODEL
The storage model is the equivalent of the conceptual model, but it describes the database organization. Not only is this file conceptually similar to the previous one, but it also uses the same XML nodes. Unlike the conceptual model, it isnt possible to split this model into several physical files. The first section of this file lists all the tables, views, stored procedures, and foreign keys that are affected. The second section describes the items listed in the first node. Regarding tables and views, the columns and primary keys are described. When it comes to stored procedures, input and output parameters are described. The description of a foreign key contains information about the table involved, the cardinality, and the delete and update rules.

MAPPING MODEL
The mapping file is completely different. Its job isnt to describe something but to compensate for the differences that exist between the two previous models. This is where the real magic of mapping happens: you map a class to one or multiple tables, map one table to one or multiple classes, define inheritance mapping, and map stored procedures for both updates and object retrieval. There is only one important node in this file: it associates the class to a table and can be repeated more than once to ensure that a class can be mapped against multiple tables, and vice versa. Like the storage description file and unlike the conceptual file, the mapping file cant be split into multiple files.

Tips to improve Entity Framework Performance


LINQ to Entity is a great ORM for querying and managing database. It offers a lot of things, so it is mandatory to know about performance of it. These are right up to a certain point as LINQ comes with its own penalties. There are some tips and tricks that we should keep in mind while desiging and query database using entity framework ORM. Here is a list of some tips that I would like to share with you.
Avoid to put all the DB Objects into One Single Entity Model

Entity Model specifies a single unit of work, not all our database. If we have many database objects that are not connected to one another or these(log tables, objects used by batch processes,etc.) are not used at all. Hence these objects are consuming space in the memory and cause performance degrades. So try to make separate entity models of related database objects.
Disable change tracking for entity if not needed

Whenever you retrieve the data only for reading purpose, not for modification then there is no need of object tracking. So disable object tracking by using MergeOption as below:
NorthwindDataContext context = new NorthwindDataContext() context.tblCities.MergeOption = MergeOption.NoTracking;

This option allow us to turn off the object cache and unnecessary identity management of the objects.
Use Pre-Generating Views to reduce response time for first request

When the object of ObjectContext is created first time in the application, the entity framework creates a set of classes that is required to access the database. This set of classes is called view and if your data model is large then creating the view may delay the web application response to the first request for a page. We can reduce this response time by creating view at compile time by using T4 template or EdmGen.exe command-line tool.
Avoid fetching all the fields if not required

Avoid fetching not required fields from the database. Suppose I have table of Customer with 20 fields and I am interested only in three fields - CustomerID, Name, Address then fetch only these three fields instead of fetching all the fields of the Customer table.
//Bad Practice var customer = (from cust in dataContext.Customers select cust).ToList(); //Good Practice var customerLite = (from cust in dataContext.Customers select new { customer. CustomerID, customer.Name, customer.Address }). ToList ();

Choose appropriate Collection for data manipulation

In linq we have Var, IEnumerable, IQueryable, IList type collection for data manipulation. Each collection has its importance and performance impact on the query,

so beware of using all these collection for data manipulation. For learning difference among all these collection refer my articles IEnumerable VS IQueryable, IEnumerable VS IList and Var VS IEnumerable.
Use Compiled Query wherever needed

Make a query to compiled query if it is frequently used to fetch records from the database. This query is slow in first time but after that it boost the performance significantly. We use Compile method of CompiledQuery class for making compiled query. Suppose you required to retrieve customers details again and again based on city then make this query to compiled query like as
// create the entity object NorthwindEntities mobjentity = new NorthwindEntities(); //Simple Query IQueryable lstCus = from customer in mobjentity.tblCustomers where customer.City == "Delhi" select customer; //Compiled Query Func> compiledQuery = CompiledQuery.Compile>( (ctx, city) =>from customer in ctx.Customers where customer.City == city select customer);

In above query we are passing the string parameter city for filtering the records. For more about anonymous method.
Retrieve only required number of records

When we are binding data to grid or doing paging, retrieve only required no of records to improve performance. This can achieved by using Take,While and Skip methods.
// create the entity object NorthwindEntities mobjentity = new NorthwindEntities(); int pageSize=10,startingPageIndex=2; List lstCus = mobjentity.tblCustomers.Take(pageSize) .Skip(startingPageIndex * pageSize) .ToList();

Avoid using Contains

In LINQ, we use contains method for checking existence. It is converted to "WHERE IN" in SQL which cause performance degrades.
Avoid using Views

Views degrade the LINQ query performance costly. These are slow in performance and impact the performance greatly. So avoid using views in LINQ to Entities.
Debug and Optimize LINQ Query

If you want to debug and optimize your query then LINQ Pad is a great tool for this purpose. I am a big fan of LINQ Pad. It is very useful for query construction, debugging and optimization.
IQueryable lstCus = from customer in mobjentity.tblCustomers where customer.City == "Delhi" select customer; lstCus.Dump();

Dump method of LINQ Pad give the result of above query in the result window.

Introduction to CSS
CSS stands for Cascading Style Sheets.CSS is a language that you can use to define styles against any HTML element. These styles are set using CSS properties.For example, you can set font properties (size, colors, style etc), background images, border styles, and much more.Using CSS, We can define all our common styles in an external Style Sheet. This way, if we want to change every occurence of a style throughout our site, we only need to update one place. Till now, there are css1, css2, css3 versions are used.

Benefits of CSS
There are following benefits :

CSS saves time


In html, we have to set the font face, size, colour, style etc for each and every element whenever it occurs on a page. With CSS, we only have to specify these details once for any element. CSS will automatically apply the specified styles whenever that element occurs.

Faster Page loading


Using css we have to do less code means page is loaded fastly.

Easy maintenance
To change the style of an element, we only have to make a change in one place.

Superior styles to HTML

CSS has a much wider array of attributes than HTML.

Limitations of CSS
The known issue is Browser compatibility issue. Browsers have varying levels of compliance with Style Sheets. This means that some Style Sheet features are supported and some aren't. To confuse things more, some browser manufacturers decide to come up with their own proprietary tags. Fortunately, browser compatibility is becoming less of an issue as the latest browser versions are much more standards-compliant than their earlier counterparts.

CSS IDs
The id selector is used to specify a style for a single, unique element. It is defined with a "#". Example : #para{ text-align:left; color:blue;}

CSS Classes
The class selector is used to specify a style for a group of elements. class selector is most often used on several elements. It is defined with a "." Example :.para {text-align:left;color:blue;}

When to use Classes ?


We should use classes when our style needs to be applied multiple times on the same page. For example : you might have many h1 elements that need the same style applied.

When to use IDs ?


We should use IDs if only one element on the page should have the style applied and/or we need a unique identifier for that element. For example : we might assign an ID to a div tag which contains our left menu. The styles for this ID could contain the position, background-color, float properties, size etc. We probably wouldn't want any other element on the page to use this particular style.

CSS Inline, block and none display style

During creation of an HTML page using CSS, it is essential to know the HTML elements display behavior. HTML elements have three display style options inline, block and none. Each option has its significant in the designing of HTML page. The basic difference among these display options is very important to know in order to use CSS efficiently. In this article, I will expose the basic difference among these display options.

Block
1. 2. 3. 4. 5. Block display elements makes a separate block with a new line before and after. It takes the full available width based on its parent element or container. Using CSS we can fix height and width of block elements. It can have other inline or block elements. <div>, <h1><h6>, <p>, <ul>, <ol>, <dl>, <li>, <dt>, <dd>,<table>, <blockquote>, <pre>,<form> are displayed as block naturally.

Inline

6. Inline display elements stay with the flow of the document and dont force the new line. 7. It takes the width as it needs. 8. Using CSS we cant fix height and width of inline elements. 9. It can have only inline elements. 10. <span>, <a>, <strong>, <em>, <img />, <abbr>, <acronym>, <br>,<input> are displayed as inline naturally.

None
11. Some tags, like <meta />,<script> and <style> are not visible naturally. We can change the display style of block elements to inline and vice-versa.

Examples of block and inline elements A paragraph (html block element <p>)
Paragraph width will be equal to the container width Paragraph height will be equal to its content.

A paragraph with fixed height and width


The width will be equal to 450px (width:450px;), and the height will be equal to 150px (height:150px;).

A paragraph converted into an inline element using display:inline;


This paragraph is now an inline element. The width and height taken by it will be acc. to its content.

An anchor tag (html inline element <a>)


The width and height taken by it will be acc. to its content.

An anchor tag with fixed height and width(to show that it does not work)
We cant set a fixed width and/or height to an inline element.

An anchor tag converted into a block element using display:block;


This anchor tag is now a block element. The width will be equal to the its container. The height will be equal to the its content.

Convert string to xml and xml to string using javascript


Sometimes we need to parse xml into string and string into xml. Different browsers parse xml to string and vice-versa in different ways. Here, I am sharing cross browser compatible methods to parse xml.

Parse XML to String


<script type="text/javascript" language="javascript"> function XMLToString(oXML) { //code for IE if (window.ActiveXObject) { var oString = oXML.xml; return oString; } // code for Chrome, Safari, Firefox, Opera, etc. else { return (new XMLSerializer()).serializeToString(oXML); } } </script>

Parse String to XML


<script type="text/javascript" language="javascript"> function StringToXML(oString) { //code for IE if (window.ActiveXObject) { var oXML = new ActiveXObject("Microsoft.XMLDOM"); oXML.loadXML(oString); return oXML; } // code for Chrome, Safari, Firefox, Opera, etc.

} </script>

else { return (new DOMParser()).parseFromString(oString, "text/xml"); }

Restrict user to enter numeric value in textbox using javascript


Due to some reasons (like dont allow to enter chars in Price TextBox), we restrict users to enter chars in TextBox. We can implement this functionality by using below method.
1. <script type="text/javascript"> 2. function checkNumeric(event) { 3. var kCode = event.keyCode || e.charCode; // for cross browser check 4. //FF and Safari use e.charCode, while IE use e.keyCode 5. // that returns the ASCII value 6. if ((kCode > 57 || kCode < 48) && (kCode != 46 && kCode != 45)) { 7. //code for IE 8. if (window.ActiveXObject) { 9. event.keyCode = 0 10. return false; 11. } 12. else 13. { 14. event.charCode= 0 15. } 16. } 17. } 18. </script> 19. <asp:TextBox ID="TextBox1" runat="server" onkeypress="return checkNumeric(event); ></asp:TextBox>

Introduction to JQuery
JQuery is a cross-browser JavaScript library that is developed to simplify the client-side scripting of HTML.It was released in january 2006 at BarCamp NYC by John Resig. JQuery is free, easy to use and open source scripting language. JQuery's syntax are easy. Using Jquery we can select DOM elements, create animations, handle different types of events, and develop ajax based applications. JQuery also provides facilities for developers to create own plugins on top of the JavaScript library. Using these capabilities, developers are able to create high level interaction and animation, advanced effects, theme-able widgets. This contributes to the formation of interactive and dynamic web pages.

Features of JQuery
JQuery is awesome scripting library. I am using it from one year and I am very much impressed to Jquery. I like it and find myself much comfortable to work with it.There are following features of JQuery : 1. 2. 3. 4. 5. 6. 7. 8. DOM traversal and modification (including support for CSS 1-3). HTML element selections. HTML element manipulation. CSS manipulation. Effects and animations. Extensibility through plug-ins. Ajax and Events Utilities - such as browser version and the each function.

Where to put our scripts?


1. Between the HTML document head tags. 2. Within the HTML document body (i.e. between the body tags). 3. In an external file (and link to it from your HTML document).

First JQuery Program


1. <html> 2. <head> 3. <script type="text/javascript" src="jquery.js">/script> 4. <script type="text/javascript"> 5. $(document).ready(function(){ 6. $("button").click(function(){ 7. $("p").hide(); 8. }); 9. }); 10. </script> 11. </head> 12. <body> 13. <h2>Welcome To JQuery World !!</h2> 14. <p>This is a JQuery paragraph.</p> 15. <p>This is another JQuery paragraph.</p> 16. <button type="button">Click me</button> 17. </body> 18. </html>

Note

1. Both Google and Microsoft provides good support for jQuery.If you do not want to store the jQuery library on your website or own computer, you can load the CDN jQuery core file from Google or Microsoft.You can download the latest version of JQuery using following links.

http://ajax.microsoft.com/ajax/jquery/jquery-1.7.min.js http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js 2. You can download JQuery 1.7 version cheat sheet from here JQuery 1.7 Cheat Sheet

Disable cut, copy and paste in textbox using jquery, javascript


Due to some reasons (like dont allow to copy Email from Email TextBox to Confirm Email TextBox), we restrict users to copy, paste and cut contents from TextBox by using CTRL+C, CTRL+V and CTRL+X. We can implement this functionality by using below methods.

Disable cut, copy & paste using Javascript When we don't want to display any message on cut, copy & paste
1. <asp:TextBox ID="TextBox1" runat="server" oncopy="return false" onpaste="return false" oncut="return false"></asp:TextBox>

When we want to display an alert message on copy, paste and cut


2. <script language="javascript" type="text/javascript"> 3. function DisableCopyPaste (e) 4. { 5. // Message to display 6. var message = "Cntrl key/ Right Click Option disabled"; 7. // check mouse right click or Ctrl key press 8. var kCode = event.keyCode || e.charCode; 9. //FF and Safari use e.charCode, while IE use e.keyCode 10. if (kCode == 17 || kCode == 2) 11. { 12. alert(message); 13. return false; 14. } 15. } 16. </script> 17. <asp:TextBox ID="TextBox1" runat="server" onKeyDown="return DisableCopyPaste(event)"onMouseDown="return DisableCopyPaste (event)"></asp:TextBox>

Disable cut, copy & paste using JQuery


1. <script type="text/javascript"> 2. $(document).ready(function() { 3. $('#TextBox1').bind('copy paste cut',function(e) { 4. e.preventDefault(); //disable cut,copy,paste

5. alert('cut,copy & paste options are disabled !!'); 6. }); 7. }); 8. </script> 9. <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>

Get file size before upload using jquery


File uploading functionality is generally used by the developers. Before uploading file on the server, to know the size of file is a good practice. By knowing file size, we can restrict the end user to upload large size files on the server since we have limited space on the server. We should check uploaded file size on server side as well client side. In this article I am going to expose how you can get size of file before uploading on client side using JQuery. For more help refer the article Asp.Net asynchronous file upload using jquery.

Example to get file size before upload using JQuery


1. <html xmlns="http://www.w3.org/1999/xhtml"> 2. <head> 3. <title>Get File Size</title> 4. <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript" > </script> 5. <script type="text/javascript"> 6. function GetFileSize(fileid) { 7. try { 8. var fileSize = 0; 9. //for IE 10. if ($.browser.msie) { 11. //before making an object of ActiveXObject, 12. //please make sure ActiveX is enabled in your IE browser 13. var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value; 14. var objFile = objFSO.getFile(filePath); 15. var fileSize = objFile.size; //size in kb 16. fileSize = fileSize / 1048576; //size in mb 17. } 18. //for FF, Safari, Opeara and Others 19. else { 20. fileSize = $("#" + fileid)[0].files[0].size //size in kb 21. fileSize = fileSize / 1048576; //size in mb 22. } 23. alert("Uploaded File Size is" + fileSize + "MB"); 24. } 25. catch (e) { 26. alert("Error is :" + e); 27. } 28. } 29. </script> 30. </head> 31. <body>

32. <form name="upload" action=""> 33. <input type="file" name="fUpload" id="fUpload" /> 34. <input type="button" value="Get File Size" onclick="GetFileSize('fUpload');" /> 35. </form> 36. </body> 37. </html>

Example to get file size before upload in Asp.Net using JQuery


Using above defined function "GetFileSize", we can also get file size in Asp.net also like as :
1. <form id="form1" runat="server"> 2. <asp:FileUpload ID="fUpload" runat="server" /> 3. <asp:Button ID="btnGetSize" runat="server" Text="Button" OnClientClick="GetFileSize('fUpload');" /> 4. </form>

Above example will work on all browsers including IE, FF, Chrome, Safari, Opera etc.

Introduction to LINQ
LINQ stands for Language-Integrated Query. Basically LINQ address the current database development model in the context of Object Oriented Programming Model. If some one wants to develop database application on .Net platform the very simple approach he uses ADO.Net. ADO.Net is serving as middle ware in application and provides complete object oriented wrapper around the database SQL.So developer must have good knowledge of object oriented concept as well as SQL to develop an application. But incase of Linq SQL statements are become part of the C# and VB.Net code so there are less chance of mistake. LINQ enables developers to query data sources using a query like syntax with both C# and VB.NET. Using LINQ we can query any database and collection.

LINQ Flavors LINQ to Objects


It provides the facility to query any kind of C# in-memory objects, like as arrays, lists, generic list and other collection types.LINQ to object query returns IEnumerable collection. It provides a new approach to query collection with powerful filtering, ordering and grouping capablities with minimum code.

LINQ to Ado.Net
LINQ to ADO.NET includes different flavors of LINQ to query data from different databases like as Microsoft SQL Server, Oracle, and others. It has following flavours

LINQ to SQL
It is specifically designed for working with Sql Server database. It provides runtime infrastructure for managing relational data as objects. It also supports transactions, views and stored procedures. It is an object-relational mapping (ORM) framework that allow 1-1 mapping of Sql Server database to .net classes. In this mapping the classes that match the database table are created automatically from the database itself and we can use these classes immediately.

LINQ to DataSet
It is an easy and faster way to query data cached in a DataSet object. It also allow LINQ to query over any database that can be query with Ado.Net.

LINQ to Entities
In many ways it is very similar to LINQ to SQL. It uses a conceptual Entity Data Model (EDM). The ADO.NET Entity Framework has been improved in .NET framework 4.0 to query any database like Sql Server, Oracle, MySql, DB2 and many more.

LINQ to XML
It provides an improved XML programming interface. Using this we can query, modify xml document and also save document after modification. System.Xml.Linq namespace contains classes for LINQ to XML.

PLINQ (Parallel LINQ)


PLINQ was introduced in .Net framework 4.0. It extends LINQ to Objects with a new parallel programming library. Using this, we can break/split up a query to execute simultaneously/parallel on different processors.

Different Types of LINQ Joins


There are Different Types of SQL Joins which are used to query data from more than one tables. In this article, I would like to share how joins work in LINQ. LINQ has a JOIN query operator that provide SQL JOIN like behavior and syntax. Let's see how JOIN query operator works for joins. This article will explore the below different types of joins in LINQ. 1. 2. 3. 4. INNER JOIN LEFT OUTER JOIN CROSS JOIN GROUP JOIN

The JOIN query operator compares the specified properties/keys of two collections for equality by using the EQUALS keyword. By default, all joins queries written by the JOIN keyword are treated as equijoins.

LINQ PAD for running and debugging LINQ Query


I am a big fan of LINQ Pad since it allow us to run LINQ to SQL and LINQ to Entity Framework query and gives the query output. Whenever, I need to write LINQ to SQL and LINQ to Entity Framework query then, I prefer to write and run query on LINQ PAD. By using LINQ PAD, you can test and run your desired LINQ query and avoid the head-ache for testing LINQ query with in Visual Studio. You can download the LINQ Pad script used in this article by using this link. In this article, I am using LINQ PAD for query data from database. It is simple and useful. For more help about LINQ PAD refer the link. You can download the database script used in this article by using this link. Suppose we following three tables and data in these three tables is shown in figure.

INNER JOIN
Inner join returns only those records or rows that match or exists in both the tables.
C# Code
var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID orderby od.OrderID select new { od.OrderID, pd.ProductID, pd.Name, pd.UnitPrice, od.Quantity, od.Price, }).ToList();

LINQ Pad Query

INNER JOIN among more than two tables


Like SQL, we can also apply join on multiple tables based on conditions as shown below.

C# Code
var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID join ct in dataContext.tblCustomers on od.CustomerID equals ct.CustID orderby od.OrderID select new { od.OrderID, pd.ProductID, pd.Name, pd.UnitPrice, od.Quantity, od.Price, Customer=ct.Name //define anonymous type Customer }).ToList();

LINQ Pad Query

INNER JOIN On Multiple Conditions


Sometimes, we required to apply join on multiple coditions. In this case, we need to make two anonymous types (one for left table and one for right table) by using new keyword then we compare both the anonymous types.
C# Code
var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID join ct in dataContext.tblCustomers on new {a=od.CustomerID,b=od.ContactNo} equals new {a=ct.CustID,b=ct.ContactNo} orderby od.OrderID select new { od.OrderID, pd.ProductID, pd.Name, pd.UnitPrice, od.Quantity, od.Price, Customer=ct.Name //define anonymous type Customer }).ToList();

LINQ Pad Query

NOTE

1. Always remember, both the anonymous types should have exact same number of properties with same name and datatype other wise you will get the compile time error "Type inferencce failed in the call to Join". 2. Both the comparing fields should define either NULL or NOT NULL values. 3. If one of them is defined NULL and other is defined NOT NULL then we need to do typecasting of NOT NULL field to NULL data type like as above fig.

LEFT JOIN or LEFT OUTER JOIN


LEFT JOIN returns all records or rows from left table and from right table returns only matched records. If there are no columns matching in the right table, it returns NULL values. In LINQ to achieve LEFT JOIN behavior, it is mandatory to use "INTO" keyword and "DefaultIfEmpty()" method. We can apply LEFT JOIN in LINQ like as :
C# Code
var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID into t from rt in t.DefaultIfEmpty() orderby pd.ProductID select new { //To handle null values do type casting as int?(NULL int) //since OrderID is defined NOT NULL in tblOrders OrderID=(int?)rt.OrderID, pd.ProductID, pd.Name, pd.UnitPrice, //no need to check for null since it is defined NULL in database rt.Quantity, rt.Price, }).ToList();

LINQ Pad Query

CROSS JOIN
Cross join is a cartesian join means cartesian product of both the tables. This join does not need any condition to join two tables. This join returns records or rows that are multiplication of record number from both the tables means each row on left table will related to each row of right table. In LINQ to achieve CROSS JOIN behavior, there is no need to use Join clause and where clause. We will write the query as shown below.
C# Code
var q = from c in dataContext.Customers from o in dataContext.Orders select new { c.CustomerID, c.ContactName, a.OrderID, a.OrderDate };

LINQ Pad Query

GROUP JOIN
Whene a join clause use an INTO expression, then it is called a group join. A group join produces a sequence of object arrays based on properties equivalence of left collection and right collection. If right collection has no matching elements with left collection then an empty array will be produced.
C# Code
var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID into t orderby pd.ProductID select new { pd.ProductID, pd.Name, pd.UnitPrice, Order=t }).ToList();

LINQ Pad Query

Basically, GROUP JOIN is like as INNER-EQUIJOIN except that the result sequence is organized into groups.

GROUP JOIN As SubQuery


We can also use the result of a GROUP JOIN as a subquery like as:
C# Code
var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID into t from rt in t where rt.Price>70000 orderby pd.ProductID select new { rt.OrderID, pd.ProductID, pd.Name, pd.UnitPrice, rt.Quantity, rt.Price, }).ToList();

LINQ Pad Query

Create xml from database using LINQ

XML data is often used to transfer data from one application to another. Since XML is language independent, hence it is a good choice to use xml for transferring data between two different platform applications. In C#, it is easy to make xml from database by using LINQ to SQL and LINQ to XML.

Create XML from Database


Suppose we have below table in database. Now I want to make xml of all the products which have stock greater than 0. Here I am using LINQ Pad to query data from the database. It is a great tool to query data from database using LINQ to SQL, LINQ to XML, LINQ to Entity Framework.
CREATE TABLE Product ( ProductID int IDENTITY(1,1) NOT NULL, ProductName varchar(50) NOT NULL, Price float NOT NULL, Stock int NOT NULL INTO INTO INTO INTO INTO INTO Product Product Product Product Product Product (ProductName,Price,Stock)VALUES('P001',12.12,100) (ProductName,Price,Stock)VALUES('P002',102.12,200) (ProductName,Price,Stock)VALUES('P003',104.12,500) (ProductName,Price,Stock)VALUES('P004',108.12,100) (ProductName,Price,Stock)VALUES('P005',72.12,10) (ProductName,Price,Stock)VALUES('P006',72.12,0)

) GO INSERT INSERT INSERT INSERT INSERT INSERT GO SELECT

* FROM Product

Now, query the data from above table using LINQ. We can also save the output to xml file.

//Export above xml to xmlfile XElement.Save(Server.MapPath(@"~/export.xml"));

IEnumerable VS IQueryable
In LINQ to query data from database and collections, we use IEnumerable and IQueryable for data manipulation. IEnumerable is inherited by Iqueryable, hence it has all the features of it and except this, it has its own features. Both have its own importance to query data and data manipulation. Lets see both the fetures and take the advantage of both the fetures to boost your LINQ Query performance.

IEnumerable
1. IEnumerable exists in System.Collections Namespace.

2. IEnumerable can move forward only over a collection, it cant move backward and between the items. 3. IEnumerable is best to query data from in-memory collections like List, Array etc. 4. While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data. 5. IEnumerable is suitable for LINQ to Object and LINQ to XML queries. 6. IEnumerable supports deferred execution. 7. IEnumerable doesnt supports custom query. 8. IEnumerable doesnt support lazy loading. Hence not suitable for paging like scenarios. 9. Extension methods supports by IEnumerable takes functional objects.

IEnumerable Example
MyDataContext dc = new MyDataContext (); IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S")); list = list.Take<Employee>(10);

Generated SQL statements of above query will be :


SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0] WHERE [t0].[EmpName] LIKE @p0

Notice that in this query "top 10" is missing since IEnumerable filters records on client side

IQueryable
1. IQueryable exists in System.Linq Namespace. 2. IQueryable can move forward only over a collection, it cant move backward and between the items. 3. IQueryable is best to query data from out-memory (like remote database, service) collections. 4. While query data from database, IQueryable execute select query on server side with all filters. 5. IQueryable is suitable for LINQ to SQL queries. 6. IQueryable supports deferred execution. 7. IQueryable supports custom query using CreateQuery and Execute methods. 8. IQueryable support lazy loading. Hence it is suitable for paging like scenarios. 9. Extension methods supports by IEnumerable takes expression objects means expression tree.

IQueryable Example
MyDataContext dc = new MyDataContext (); IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S")); list = list.Take<Employee>(10);

Generated SQL statements of above query will be :


SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0] WHERE [t0].[EmpName] LIKE @p0

Notice that in this query "top 10" is exist since IQueryable executes query in SQL server with all filters.

IEnumerable VS IList
In LINQ to query data from collections, we use IEnumerable and IList for data manipulation.IEnumerable is inherited by IList, hence it has all the features of it and except this, it has its own features. IList has below advantage over IEnumerable. In previous article, I explain the difference between IEnumerable and IQueryable.

IList
1. IList exists in System.Collections Namespace. 2. IList is used to access an element in a specific position/index in a list. 3. Like IEnumerable, IList is also best to query data from in-memory collections like List, Array etc. 4. IList is useful when you want to Add or remove items from the list. 5. IList can find out the no of elements in the collection without iterating the collection. 6. IList supports deferred execution. 7. IList doesnt support further filtering.

IEnumerable
1. IEnumerable exists in System.Collections Namespace. 2. IEnumerable can move forward only over a collection, it cant move backward and between the items. 3. IEnumerable is best to query data from in-memory collections like List, Array etc. 4. IEnumerable doent support add or remove items from the list. 5. Using Ienumerable we can find out the no of elements in the collection after iterating the collection. 6. IEnumerable supports deferred execution. 7. IEnumerable supports further filtering.

Var VS IEnumerable
In previous article I explain the difference between IEnumerable and IQuerable, IEnumerable and IList. In this article I expose the difference between Var and IEnumerable. IEnumerable is an interface that can move forward only over a collection, it cant move backward and between the items. Var is used to declare implicitly typed local variable means it tells the compiler to figure out the type of the variable at compilation time. A var variable must be initialized at the time of declaration. Both have its own importance to query data and data manipulation.

Var Type
Since Var is anonymous types, hence use it whenever you don't know the type of output or it is anonymous. Suppose you are joining two tables and retrieving data from both the tables then the result will be an Anonymous type.
1. 2. 3. 4. 5. 6. 7. 8. var q =(from e in tblEmployee join d in tblDept on e.DeptID equals d.DeptID select new { e.EmpID, e.FirstName, d.DeptName, });

In above query, result is coming from both the tables so use Var type.
1. var q =(from e in tblEmployee where e.City=="Delhi" select new { 2. e.EmpID, 3. FullName=e.FirstName+" "+e.LastName, 4. e.Salary 5. });

In above query, result is coming only from single table but we are combining the employee's FirstName and LastName to new type FullName that is annonymous type so use Var type. Hence use Var type when you want to make a "custom" type on the fly. More over Var acts like as IQueryable since it execute select query on server side with all filters. Refer below examples for explanation.

IEnumerable Example
1. MyDataContext dc = new MyDataContext (); 2. IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S")); 3. list = list.Take<Employee>(10);

Generated SQL statements of above query will be :


1. SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0] WHERE [t0].[EmpName] LIKE @p0

Notice that in this query "top 10" is missing since IEnumerable filters records on client side

Var Example
1. MyDataContext dc = new MyDataContext (); 2. var list = dc.Employees.Where(p => p.Name.StartsWith("S")); 3. list = list.Take<Employee>(10);

Generated SQL statements of above query will be :


1. SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0] WHERE [t0].[EmpName] LIKE @p0

Notice that in this query "top 10" is exist since var is a IQueryable type that executes query in SQL server with all filters.

IEnumerable Type
IEnumerable is a forward only collection and is useful when we already know the type of query result. In below query the result will be a list of employee that can be mapped (type cast) to employee table.
1. IEnumerable<tblEmployee> lst =(from e in tblEmployee 2. where e.City=="Delhi" 3. select e);

Note

1. 2. 3. 4.

Use Var type when you want to make a "custom" type on the fly. Use IEnumerable when you already know the type of query result. Var is also good for remote collection. IEnumerable is good for in-memory collection.

Object-Oriented Programming Concepts


OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts.Below are object oriented programming concepts :

Object
Object is representative of the class and is responsible for memory allocation of its data members and member functions.An object is a real world entity having attributes (data type) and behaviors (functions). An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object behavior. For example, the hand can grip something or a Student (object) can give the name or address

Class
Class is a data structure that contains data members (constants files, events), member function methods, properties, constructor, destructor, indexers and nested type.Basically 1. It is a user defined data type. 2. It is a reference type. 3. Infact class is a tag or template for object.

Encapsulation

Encapsulation is a mechanism of binding the data member & member function into a single unit known as class.Encapsulation provides a way for abstraction.In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes.

Data abstraction
Data abstraction is a mechanism to provide the essential features without describing the background details. Means provide the functions to access the hidden (private) data. The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs.

Data Hiding
Data hiding is a mechanism to hide the internal structure of an object from rest of the program.In a class private members are hidden from the rest of the program, hence it supports data hiding. Data hiding is also a way to implement data abstraction.

Polymorphism
Polymorphism means one thing in many form.Basically polymorphism is capability of one object to behave in multiple ways. Example : A man role changes at home, college, and outside the home. There are following types of polymorphism : 4. Static polymorphism(compile time) :It is achieved using function overloading and operator overloading. 5. Dynamic polymorphism(runtime time) : It is achieved using function overriding means using virtual function.

Difference between object oriented and object based languages


Object oriented and Object based programming languages have some different features and behaviour. In this article, I am going to expose the main difference between these two programming languages.

Object oriented language


1. Object-oriented language supports all the features of OOPs. 2. Object-oriented language doesn't has in-built object. 3. Object-oriented languages are C++, C#, Java etc.

Object based language


1. Object-based language doesn't support all the features of OOPs like Polymorphism and Inheritance 2. Object-based language has in-built object like javascript has window object. 3. Object-based languages are Javascript, VB etc.

Difference between function and method


In programming langauages we have two concepts functions and methods. functions are defined in structural language and methods are defined in object oriented langauge. The difference between both is given below :

Functions
1. Functions have independent existence means they can be defined outside of the class. Ex:- main() function in C, C++ Language 2. Functions are defined in structured languages like Pascal,C and object based language like javaScript 3. Functions are called independently. 4. Functions are self describing unit of code.
1. //function main in C 2. void main() 3. { 4. int a,b,c; 5. a=5; 6. b=6; 7. c=a+b;

8. printf("Sum is : %d",c); 9. }

Methods
1. Methods do not have independent existence they are always defined with in class. Ex:main() method in C# Language that is defined with in a class 2. Methods are defined in object oriented languages like C#, Java 3. Methods are called using instance or object. 4. Methods are used to manipuate instance variable of a class.
1. //method sum in C# 2. class demo 3. { 4. int a,b,c; 5. public void sum() 6. { 7. a=5; 8. b=6; 9. c=a+b; 10. Console.WriteLine("Sum is : {0}",c); 11. } 12. }

SQL Server 2012 New Features and Programmability Enhancements


SQL Server 2012 has a powerful set of fetures to increase productivity of developers and database administrators. SQL Server 2012 has a new SSMS that is built on Visual Studio 2010 and support various productivity features of Visual Studio 2010 like multi monitor support and pull out the tabs from main work area to different monitor or out side the IDE. Now, you can also use Visual Studio short-cut keys with SQL Server 2012. More over SQL Server 2012 supports business intellisense and debugging like Visual Studio 2010.

SQL Server 2012 Programmability Enhancements


SQL Server 2012 supports a great programmability enhancements and functions that developers and database adminsitrators will enjoy. Some new programmability enhancements and functions are listed below:

T-SQL THROW Statement


Now SQL Server 2012 has improved error handling by introducing throw statement for throwing exception in T-SQL. However this statement has some limitations and does not provide powerful features like RAISERROR.

Conversion Functions
SQL Serve 2012 has support for new conversion functions TRY_CONVERT, and TRY_PARSE for convering numeric, date, and time values to desired format. These functions are very helpful while programming T-SQL.

T-SQL built-in pagination


SQL Server 2012 also supports built-in pagination with the help of OFFSET and FETCH like MySQL. Actually, OFFSET and FETCH will act as a replacement for TOP in SQL Server.

1. 2. 3. 4. 5. 6.

--Suppose Employee tables has 500 records --Below query skip 200 rows and fetch the next 20 records SELECT EmpID, EmpName, Salary FROM dbo.Employee ORDER BY EmpID OFFSET 200 ROWS FETCH NEXT 20 ROWS ONLY

T-SQL Sequence
SQL Server 2012 also supports sequence like Oracle database. It works like as IDENTITY field without being a field. The main advantage of sequence is that you can use it in the same way as GUIDs and with better performance than GUIDs when used as a clustered index key.
7. --Create Sequence object 8. CREATE SEQUENCE objSequence 9. START WITH 1 10. INCREMENT BY 1; 11. --Create Employee object 12. DECLARE @Employee TABLE 13. ( 14. ID int NOT NULL PRIMARY KEY, 15. FullName nvarchar(100) NOT NULL 16. ) 17. --Insert values 18. INSERT @Employee (ID, FullName) 19. VALUES (NEXT VALUE FOR objSequence, 'Mohan'), 20. (NEXT VALUE FOR objSequence, 'Deepak'), 21. (NEXT VALUE FOR objSequence, 'Pavan'); 22. --Show data 23. SELECT * FROM @Employee

Metadata Discovery Enhancements


SQL Server 2012 also has improved metadata discovery, which allow you to determine the shape of projected output from queries, tables, stored procedure, views, and other objects. As a result SQL Server supports business intellisense and debugging.

T-SQL Format() Function

SQL Server 2012 introduces a new function format() for formatting string data like as C#. It is a CLR based function.
24. SELECT FORMAT(GETDATE(), 'yyyy-MM-dd') AS [ISO Formatted Date], FORMAT(GETDATE(), 'yyyy-MM-dd hh:mm:ss') AS [Full ISO], FORMAT(GETDATE(), 'MMMM dd, yyyy') AS [Long-EN Date], FORMAT(22.7, 'C', 'en-US') AS [US Currency], FORMAT(99 * 2.226, '000.000') AS [Padded Decimal], FORMAT(12345678, '0,0') AS [Commas in Large Numbers]

Introduction to TFS
TFS stands for Team Foundation Server which is developed by Microsoft. Integration of TFS with Visual Studio enables a team to work together and organize their efforts to complete a project. Dot Net developers use TFS for source control, bug tracking, requirement gathering and to manage complete life cycle of software development. It has below listed features:-

Communication Enhancement
TFS enhance the communication among team members by ensuring that no information or work is lost when a team member hand over his task to team. Project of the team is stored on the TFS and every team member has its own credentials to connect to TFS for accessing the project. TFS provides a central location to team project and each team member coordinate his work at this location.

Team Explorer
All members of a team work together on the team project by using Team Explorer in Visual Studio. Team Explorer connects to the TFS and displays team projects from the server. By using Team Explorer, every team member can get updated work items, projects documents and task to do.

Roles
Roles can be defined on team project that is on TFS. Each role represents one or more disciplines that are required to successful completion of the team project.

Alerts
TFS also provides alerts that are sent to team members by e-mail when something has changed on the team project. We can customize alerts on TFS according to our need.

Source Control

TFS allow the team to manage all source files for a project. We can also add non-source files such as important project documents, project plans etc. to TFS.

Builds
TFS Build enables the team to create and manage product builds regularly. TFS Build also provides build reports on the status and quality of each build.

Tracking Work Status


Using TFS project head can track the assigned work status to developers to understand the health of the project.

Work Item History


All working items are logged on TFS with all changes. Anyone can review the complete history of activity on a work item at any time. The working item history can be exported into Microsoft Excel.

Reports
Reports related to track status and information (like as work item changes, check-ins and status of product builds etc.) about the project are stored in a database on the TFS

Visual Studio Debug VS Release mode


When we want to deploy our web application to live/local server, then we have two options for making built Release mode and Debug mode. Both the modes have own importance and characteristics. The details about Release mode and Debug mode are as:

Debug Mode
Developer use debug mode for debugging the web application on live/local server. Debug mode allow developers to break the execution of program using interrupt 3 and step through the code. Debug mode has below features: 1. Less optimized code 2. Some additional instructions are added to enable the developer to set a breakpoint on every source code line. 3. More memory is used by the source code at runtime. 4. Scripts & images downloaded by webresource.axd are not cached. 5. It has big size, and runs slower.

Release Mode
Developer use release mode for final deployment of source code on live server. Release mode dlls contain optimized code and it is for customers. Release mode has below features: 1. More optimized code 2. Some additional instructions are removed and developer cant set a breakpoint on every source code line. 3. Less memory is used by the source code at runtime. 4. Scripts & images downloaded by webresource.axd are cached. 5. It has small size, and runs fast.
Note

There is no difference in functionality of a debug dll and a release dll. usually, when we compile code in debug mode, we have a corresponding .pdb (program database) file. This .pdb file contains information that enables the debugger to map the generated IL (intermediate language) to source code line number. It also contains the names of local variables in the source code.

Set Compilation Mode in Visual Studio

We can set the compile mode in visual studio as shown in below fig.

Visual Studio 2008, 2010, 2011, 2012 Keyboard Shortcuts Keys


Shortcut keys play an important role to increase the output. Developers work at least 6 to 8 hours on daily basis on Visual Studio. If the developer knows the shortcut keys, he can keep away from using of mouse and absolutely it will enhance productivity and reduce headache to use of mouse again and again. I am sharing some interesting and useful shortcut keys to work with Visual Studio. General Shortcut Keys

Shortcut Ctrl-X or Shift-Delete or Ctrl-L

Description Cuts entire line or Cuts the currently selected

Ctrl-Del Ctrl-C or Ctrl-Insert Ctrl-V or Shift-Insert Ctrl-Z or Alt-Backspace Ctrl-Space Ctrl-Y or Ctrl-Shift-Z Ctrl-S Ctrl-Shift-S Ctrl-P F7 Shift-F7 Shift-F8 or F8 Alt-Shift-A Ctrl-Shift-A Shift-F9 F12 Shift-F12 Ctrl-} Ctrl-Shift-}

item to the clipboard Delete next "word" Copies the currently selected item to the clipboard Pastes the item from the clipboard at the cursor location Undo the previous editing action To see intelligence dialog Redo the previous undo action Saves the current selected file Saves all files and projects Displays the Print dialog Switches from the design view to the code view in the editor Switches from the code view to the design view in the editor Navigate to compile time errors Add Existing Item(file) to selected project Add New Item(file) to selected project Display the selected item quick output means contains value while debugging Moves the cursor to the selected method, variable, class definition. Finds the reference to the selected method, variable, class or the item under the cursor Match curly braces, brackets or compiler directives Select text between matched braces, brackets or compiler directives
Text manipulation

Shortcut Tab Tab-Tab

Shift-Tab Backspace or Shift-Backspace Ctrl-K, Ctrl-C

Description Indents the currently selected line or lines by one tab stop. If there is no selection, this inserts a tab stop Complete the syntax of an item. ExampleWrite for and now press Tab-Tab, then for loop syntax will be automatically completed. Similarly it works for property, index, class syntax. Moves current line or selected lines one tab stop to the left Deletes one character to the left of the cursor Marks the current line or selected lines of code as a comment, using the correct comment

Ctrl-K, Ctrl-U Ctrl-K, Ctrl-D Ctrl-T or Shift-Enter Ctrl-U Ctrl-Shift-U Ctrl-Shift-Right Arrow Ctrl-Right Arrow Shift-End Shift-Home Shift-Alt-Arrows or Alt-Mouse Ctrl-Delete Ctrl-Backspace Ctrl-G

syntax for the programming language Removes the comment syntax from the current line or currently selected lines of code Do proper alignment of all the code of design view and code view Swaps the characters on either side of the cursor. (For example, AC|BD becomes AB| CD.) Available only in text editors Changes the selected text to lowercase characters Changes the selected text to uppercase characters Select the entire word with space from start to end Move the cursor in forward direction word by word Select the entire line from start to end Select the entire line from end to start Column wise text selection for text manipulation Deletes the word to the right of the cursor Deletes the word to the left of the cursor Jump to line number or go to line
Project related

Shortcut Ctrl-Shift-B Ctrl-N

Ctrl-Shift-N Ctrl-O Ctrl-Shift-O Ctrl-M-O Ctrl-M-P or Ctrl-M-L Ctrl-F Ctrl-H Ctrl-Shift-F Ctrl-Tab F9

Description Builds the solution Displays the New File dialog. Note: files created this way are not associated with a project. Use Ctrl-Shift-A to add a new file in a project Displays the New Project dialog Displays the Open File dialog Displays the Open Project dialog Collapse all the methods, classes, regions in the current code behind or class file Expands all the methods, classes, regions in the current code behind or class file Displays the Find dialog Displays the Replace dialog Find the reference of selected item into entire solution. Move from one opened file to another opened file in visual studio. Sets or removes a breakpoint at the current line

Ctrl-F9 F5 Ctrl-F5 F4 or Alt-Enter Ctrl-Alt-S

Ctrl-Alt-L Ctrl-Alt-X Ctrl-Alt-I

Enables or disables the breakpoint on the current line of code. The line must already have a breakpoint for this to work Runs the code with invoking the debugger. Runs the code without invoking the debugger. Displays the Properties window, which lists the design-time properties and events for the currently selected item Displays the Server Explorer window, which allows you to view and manipulate database servers, event logs, message queues, web services, and many other operating system services Displays the Solution Explorer, which lists the projects and files in the current solution Displays the Toolbox, which contains controls and other items that can be dragged into editor and designer windows Displays the Immediate window, where you can find the controls or variables values or can do data manipulation during debugging

Introduction to Web Service


Web services are components on a Web server that a client application can call by making HTTP requests across the Web. ASP.NET enables you to create custom Web services or to use built-in application services, and to call these services from any client application. Basically web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system.XML is used to encode all communications to a Web service. In simple sense, Web Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by using standard web protocols and data formats, such as : 1. Http 2. Xml 3. Soap

Example Weather Reporting

You can use Weather Reporting web service to display weather information in your personal website.

Stock Quote
You can display latest update of Share market with Stock Quote on your web site

News Headline
You can display latest news update by using News Headline Web Service in your website.

Web Service Properties


1. First, a Web service can have a public interface, defined in a common XML grammar. The interface describes all the methods available to clients and specifies the signature for each method. Currently, interface definition is accomplished via the Web Service Description Language (WSDL). 2. Second, if you create a Web service, there should be some relatively simple mechanism for you to publish this fact. Likewise, there should be some simple mechanism for interested parties to locate the service and locate its public interface. The most prominent directory of Web services is currently available via UDDI, or Universal Description, Discovery, and Integration.

Web Service Advantages


1. Since Web services are platform & language independent, hence any web services from different sources can communicate to one another. 2. Web Service messages are formatted as XML and this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.

Introduction to WCF
WCF stands for Windows Communication Foundation. It is Microsoft's latest technology that enables applications in a distributed environment to communicate with each other.WCF is Microsoft's unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing. WCF is an umbrella technology that covers ASMX web services, .NET remoting, WSE, Enterprise Service, and System.Messaging. It is designed to offer a manageable approach to

distributed computing, broad interoperability, and direct support for service orientation. WCF supports many styles of distributed application development by providing a layered architecture.

ABC of Windows Communication Foundation


What are the ABCs of WCF? "ABC" stands for address, binding and contract.

Address (Where)
It specifies the location of the service means, where the service is hosted. The service hosting URL may be like http://server/wcfService. Clients will use this location to communicate with your service.

Binding (How)
It specifies how the client will communicate to the service. We have different protocols (like http,tcp,named pipe,msmq) for the WCF to communicate to the client.

Contract (What)
It specifies what the service will do. For this purpose we have different contract like as Data Contract, Operation Contract, Message Contract, Fault Contract. I will discuss all these later.

WCF Hosting
A WCF service is a component that can be called by other applications. It must be hosted in an environment in order to be discovered and used by others. The WCF host is an application that controls the lifetime of the service. With .NET 3.0 and beyond, there are several ways to host the service.

Self hosting
A WCF service can be self-hosted, which means that the service runs as a standalone application and controls its own lifetime. This is the most flexible and easiest way of hosting a WCF service, but its availability and features are limited.

Windows services hosting


A WCF service can also be hosted as a Windows service. A Windows service is a process managed by the operating system and it is automatically started when Windows is started (if it is configured to do so). However, it lacks some critical features (such as versioning) for WCF services.

IIS hosting

A better way of hosting a WCF service is to use IIS. This is the traditional way of hosting a web service. IIS, by nature, has many useful features, such as process recycling, idle shutdown, process health monitoring, message-based activation, high availability, easy manageability, versioning, and deployment scenarios. All of these features are required for enterprise-level WCF services.

Windows Activation Services hosting


The IIS hosting method, however, comes with several limitations in the serviceorientation world; the dependency on HTTP is the main culprit. With IIS hosting, many of WCF's flexible options can't be utilized. This is the reason why Microsoft specifically developed a new method, called Windows Activation Services, to host WCF services. Windows Process Activation Service (WAS) is the new process activation mechanism for Windows Server 2008 that is also available on Windows Vista. WAS hosting is possible only with IIS 7.0.Additional WCF components also plug into WAS to provide messagebased activation over the other protocols that WCF supports, such as TCP, MSMQ, and named pipes. This allows applications that use the non-HTTP communication protocols to use the IIS features such as process recycling, rapid fail protection, and the common configuration systems that were only available to HTTP-based applications.

Calling Cross Domain WCF Service using Jquery


From last couple of days, I was trying to call a wcf service using jquery that is hosted in different domain. But every time I was failed to call wcf service from different domain. After spending much time on R&D, I found the solution and the reason why I was unable to call cross domain wcf service. Whenever you try to call a cross domain WCF Service by javascript or jquery, it behaves differently with different browsers. When you want to perform "POST" or "GET" request on cross domain wcf service or normal service using jquery/javascript or ajax, the browser actually sends an "OPTIONS" verb call to your wcf service that is not mention in your wcf method attribute. We mention there "POST" or "GET" to call a wcf service method. Hence we get error to call cross domain wcf service. We find the following request and response headers in firefox when we try to call wcf service.

Request Headers
1. OPTIONS http://myserver/MyService.svc/GetStates HTTP/1.1 2. Host: 192.168.4.156 User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0 3. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 4. Accept-Language: en-us,en;q=0.5 5. Accept-Encoding: gzip, deflate

6. Proxy-Connection: keep-alive 7. Origin: http://192.168.4.156:90 8. Access-Control-Request-Method: POST 9. Access-Control-Request-Headers: content-type 10. Pragma: no-cache 11. Cache-Control: no-cache

Response Headers
1. HTTP/1.0 405 Method Not Allowed 2. Cache-Control: private 3. Allow: POST 4. Content-Length: 1565 5. Content-Type: text/html; charset=UTF-8 6. Server: Microsoft-IIS/7.0 7. X-AspNet-Version: 4.0.30319 8. X-Powered-By: ASP.NET 9. Access-Control-Allow-Origin: * 10. Access-Control-Allow-Headers: Content-Type 11. Date: Fri, 04 May 2012 12:05:17 GMT 12. X-Cache: MISS from c1india.noida.in 13. X-Cache-Lookup: MISS from c1india.noida.in:3128 14. Via: 1.0 c1india.noida.in:3128 (squid/2.6.STABLE21) 15. Proxy-Connection: close

In above request headers the method is "OPTION" not "POST" and the response headers has content-type "text/html; charset=UTF-8" instead of "json;charset=UTF-8". To change these options we need to do some changes in web.config of hosted wcf service.

Configure WCF Cross Domain service


1. namespace CrossDomainWcfService 2. { 3. [DataContract] 4. public class Supplier 5. { 6. [DataMember] public string Name; 7. [DataMember] public string Email; 8. } 9. [ServiceContract(Namespace = "")] 10. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 11. public class MyService 12. { 13. [OperationContract] 14. [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 15. List GetSuppliers (int OrgID) 16. { 17. // Fetch data from database var q= (from tbl in mobjentity.Customer 18. where tbl.OrgID=OrgID).ToList(); 19. Listlst= new List(); 20. foreach(var supp in q) 21. {

22. Supplier msupp=new Supplier(); 23. msupp.Name=supp.Name; 24. msupp.Email=supp.Email 25. //Make Supplier List to retun 26. lst.Add(msupp); 27. } 28. return lst; 29. } 30. } 31. }

WCF Service Web.config


1. <system.webServer> 2. <modules runAllManagedModulesForAllRequests="true" /> 3. <httpProtocol> 4. <customHeaders> 5. <add name="Access-Control-Allow-Origin" value="*" /> 6. <add name="Access-Control-Allow-Headers" value="Content-Type" /> 7. </customHeaders> 8. </httpProtocol> 9. </system.webServer> 10. <system.serviceModel> 11. <behaviors> 12. . 13. . 14. . 15. </behaviors> 16. <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> 17. <standardEndpoints> 18. <webScriptEndpoint> 19. <standardEndpoint name="" crossDomainScriptAccessEnabled="true" /> 20. </webScriptEndpoint> 21. </standardEndpoints> 22. <services> 23. . 24. . 25. </service> 26. </services> 27. <bindings> 28. . 29. . 30. </bindings> 31. <client> 32. . 33. . 34. </client> 35. </system.serviceModel>

Global.asax Code
You can also define your hosted service web.config setting in Global.asax file. If you have defined setting in web.config then there is no need to do here.

1. protected void Application_BeginRequest(object sender, EventArgs e) 2. { 3. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , *); 4. if (HttpContext.Current.Request.HttpMethod == "OPTIONS" ) 5. { 6. //These headers are handling the "pre-flight" OPTIONS call sent by the browser 7. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" ); 8. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" ); 9. HttpContext.Current.Response.AddHeader("Access-Control-Max-Age" "1728000" ); 10. HttpContext.Current.Response.End(); 11. } 12. }

Wcf calling using Jquery


1. 2. 3. $.ajax({ type: "Post" url: "http://www.yourdomain.com/MyService.svc/GetSuppliers", // Location of the service 4. data: '{"OrgID"="1"}', //Data sent to server 5. contentType: "application/json;charset-uf8", // content type sent to server 6. dataType: "json", //Expected data format from server 7. success: function (msg) { 8. //Implement get data from service as you wish 9. }, 10. error: function (err) { 11. // When Service call fails 12. } 13. });

Note

1. You can define cross domain setting either in web.config or in global.asax file of your wcf service.

Error code 12031 in Ajax enabled wcf


From last couple of days I was trying to call a ajax enabled wcf service method with the help of jquery. But each and every time I am getting the error code 12031 returned by the service. I did googling for this error but I was unable to find the solution. After spending much time on R&D, I found the reason why I wa geeting this error.

In this article, I am going to share my experience with you so that you will be able to resolve this error in ajax enabled wcf service. I have the below service and code for calling wcf.
WCF Service
1. namespace WCFBAL 2. { 3. [DataContract] 4. public class Employee 5. { 6. [DataMember] 7. public int EmpID; 8. [DataMember] 9. public string Name; 10. [DataMember] 11. public int Salary; 12. [DataMember] 13. public DateTime JoiningDate; 14. } 15. [ServiceContract(Namespace = "")] 16. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 17. public class WCFBALService 18. { 19. [WebInvoke(Method = "POST")] 20. public Employee GetEmpInfo(int mEmpID) 21. { 22. try 23. { 24. //suppose you have a list of employee like as in the database 25. List lst = new List() 26. { 27. new Employee { EmpID = 1, Name = "Deepak", Salary = 12000, JoiningDate = Convert.ToDateTime("11/05/2011") }, 28. new Employee { EmpID = 2, Name = "Mohan", Salary = 18000}, 29. new Employee { EmpID = 3, Name = "Mohan", JoiningDate = Convert.ToDateTime("06/10/2011") } 30. }; 31. var q = lst.Where(m => m.EmpID == mEmpID).FirstOrDefault(); 32. Employee mobjEmp = new Employee(); 33. if (q != null) 34. { 35. mobjEmp.EmpID = q.EmpID; 36. mobjEmp.Name = q.Name; 37. mobjEmp.Salary = q.Salary; // comment this line to expect same error 38. //The no error will be raised since "Salary" field is of int type and default value of int variable is "0", so zero value will be assigned to it. 39. mobjEmp.JoiningDate = q.JoiningDate; // comment this line and provide mEmpID=1 to raise error 40. //The error will be raised since "JoiningDate" field is not being serialized because this of DateTime and this has no default value and not assign any value to it. 41. } 42. return mobjEmp;

43. } 44. catch (Exception mex) 45. { 46. return null; 47. } 48. } 49. } 50. }

WCF Service Method Calling Code


1. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> 2. $('#btn').live('click', function () { 3. // debugger; 4. var value = $('#txtEmpID').val(); 5. if (value != '') { 6. var strJSONFilterCriteria = '{"mEmpID":"' + value + '"}'; 7. $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", 8. url: '<%=ViewState["WCFBalUrl"]%>' + '/GetEmpInfo', 9. data: strJSONFilterCriteria, 10. dataType: "json", 11. error: function (msg) { 12. // debugger; 13. alert('Service call failed: ' + msg.status + ' Type :' + msg.statusText); 14. }, 15. success: function (msg) { 16. //debugger; 17. var str = "Emp ID:" + msg.d.EmpID + "\n"; 18. str += "Emp Name:" + msg.d.Name + "\n"; 19. str += "Emp Salary:" + msg.d.Salary + "\n"; 20. //str += "JoiningDate:" + new Date(parseInt(msg.d.JoiningDate.substr(6))) + "\n"; 21. alert(str); 22. } }); } 23. return false; 24. }); 25. </script> 26. <h2> 27. WCF Error Code 12031 28. </h2> 29. <p> 30. To learn more about Dot Net Tricks visit <a href="http://www.dotnettricks.com" title="Dot Net Tricks "> 31. www.dotnet-tricks.com</a>. 32. </p> 33. <p> 34. Enter Employee ID (1-3) 35. </p> 36. <p> 37. <asp:TextBox ID="txtEmpID" runat="server" ClientIDMode="Static"></asp:TextBox> 38. <asp:Button ID="btn" runat="server" Text="Get Info" ClientIDMode="Static" /> 39. </p>

Asp.Net MVC Tutorial - Getting Started with MVC3

Asp.net MVC Request Life Cycle


While programming with Asp.net MVC, you should be aware of the life of an Asp.net MVC request from birth to death. In this article, I am going to expose the Asp.net MVC Request Lifecycle. There are six main steps that happen when you make a request to an Asp.net MVC web applications:

Routing
Asp.net Routing is the first step in MVC request cycle. Basically it is a pattern matching system that matches the requests URL against the registered URL patterns in the Route Table. When a matching pattern found in the Route Table, the Routing engine forwards the request to the appropriate handler for that request. Otherwise, the routing engine returns a 404 HTTP status code against that request. When application starts at first time, it registers one or more patterns to the Route Table to tell the routing system what to do with any requests that match these patterns. An application has only one Route Table and this is setup in the Global.asax file of the application.
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); }

MvcHandler

The handler returned from the RouteTable will always be an MvcHandler and represents a particular RouteContext. Actually, MvcHandler creates a controller, and also executes the controller.

Controller
The controller determines which action method of the controller class to call, and then calls that method

View Result
The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result type can be ViewResult,

RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.

View Engine
Now the ViewResult calls into the current view engine to render the view. Controller is responsible only for preparing the data and decides which view to display by returning a ViewResult instance.

View
The data rendered by the current view engine is displayed on the view.

Understading Controllers and Actions in MVC Razor


Asp.net MVC Controllers are responsible for controlling the flow of the application execution. When you make a request (means request a page) to MVC applications , a controller is responsible for returning the response to that request. A controller can have one or more actions. A controller action can return different types of action results to a particular request.

Controller
Basically, the controller Receives input like as form values, query strings values etc. from users via the View and perform required operations on the user's inputs with the help of Model and passing the results back to the View. Actually, controllers are classes that have methods or action results and these actions results are called by the routing system to process a particular request.

Creating a Controller
For creating a controller, do right-click on the Controller folder in your mvc application and select the menu option Add, Controller. After selection the Add Controller dialog is being displayed as shown in fig. Now enter your controller name before Controller word.

In this way you have successfully created your controller as shown in fig.

Controller Actions and Helper Methods


Controller actions are methods defined in the controller class and responsible to perform required operations on the user's inputs like as form values, query strings values etc. with the help of Model and passing the results back to the View. Asp.net MVC has the following Built-in ActionResults Type and Helper methods :

ViewResult
Returns a ViewResult which renders the specified or default view by using controller View() helper method.

PartialViewResult
Returns a PartialViewResult which renders the specified or default partial view (means a view without its layout) by using controller PartialView() helper method.

RedirectResult
Returns a RedirectResult which Issues an HTTP 301 or 302 redirection to a specific URL by using controller Redirect() helper method.

RedirectToRouteResult
Returns a RedirectToRouteResult which Issues an HTTP 301 or 302 redirection to an action method or specific route entry by using controller RedirectToAction(), RedirectToActionPermanent(), RedirectToRoute(), RedirectToRoutePermanent() helper methods.

ContentResult
Returns a ContentResult which renders raw text like as "Hello, DotNet Tricks!" by using controller Content() helper method.

JsonResult
Returns a JsonResult which serializes an object in JSON format ( like as "{ "Message": Hello, World! }") and renders it by using controller Json() helper method.

JavaScriptResult
Returns a JavaScriptResult which renders a snippet of JavaScript code like as "function hello() { alert(Hello, World!); }" by using controller JavaScript() helper method. This is used only in AJAX scenarios.

FileResult
Returns a FileResult which renders the contents of a file like as PDF, DOC, Excel etc. by using controller File() helper method.

EmptyResult
Returns no result returned by an action. This has no controller helper method.

HttpNotFoundResult
Returns an HttpNotFoundResult which renders a 404 HTTP Status Code response by using controller HttpNotFound() helper method.

HttpUnauthorizedResult
Returns an HttpUnauthorizedResult which renders a 401 HTTP Status Code(means "not authorized") response. This has no controller helper method. This is used for authentication (forms authentication or Windows authentication) to ask the user to log in.

HttpStatusCodeResult

Returns an HttpStatusCodeResult which renders a specified HTTP code response. This has no controller helper method.

Difference between Asp.Net WebForm and Asp.Net MVC


Asp.net framework is a part of .net platform for building, deploying and running web applications. Now, we can develop a web application by using Asp.Net Web Form and Asp.Net MVC. In this article, I am going to expose the main difference between Asp.Net Web Form and Asp.Net MVC. Difference between Asp.Net MVC and Web Forms Asp.Net Web Forms Asp.Net Web Form follow a traditional event driven development model. Asp.Net MVC Asp.Net MVC is a lightweight and follow MVC (Model, View, Controller) pattern based development model. Asp.Net Web Form has server controls. Asp.Net MVC has html helpers. Asp.Net Web Form has state management (like Asp.Net MVC has no automatic state as view state, session) techniques. management techniques. Asp.Net Web Form has file-based URLs Asp.Net MVC has route-based URLs means means file name exist in the URLs must have URLs are divided into controllers and actions its physically existence. and moreover it is based on controller not on physical file. Asp.Net Web Form follows Web Forms Asp.Net MVC follow customizable syntax Syntax (Razor as default) In Asp.Net Web Form, Web Forms(ASPX) i.e. In Asp.Net MVC, Views and logic are kept views are tightly coupled to Code separately. behind(ASPX.CS) i.e. logic. Asp.Net Web Form has Master Pages for Asp.Net Web Form has Layouts for consistent consistent look and feels. look and feels. Asp.Net Web Form has User Controls for code Asp.Net MVC has Partial Views for code rere-usability. usability. Asp.Net Web Form has built-in data controls Asp.Net MVC is lightweight, provide full and best for rapid development with powerful control over markup and support many features data access. that allow fast & agile development. Hence it is best for developing interactive web application with latest web standards. Visual studio and Visual web developer(free) Visual studio and Visual web developer(free) are tools for developing Asp.Net Web Forms. are tools for developing Asp.Net MVC application. Asp.Net Web Form is not Open Source. Asp.Net Web MVC is an Open Source.

Removing the Web Form View Engine for better performance of Razor View Engine
By default MVC is configured to resolve a view by searching the views that match the Web Form view engine's naming conventions first. After that MVC begins search for the views that match the Razor view engine's naming conventions as shown in below fig.

So, If are not using ASPX views in your MVC applications then the checking four unused locations first for every return View() and Html.RenderPartial is quite wasteful and time consuming. After removing Web Form engine, Razor View Engine will be twice as fast with the Web Form engine.

Removing the Web Form (ASPX) view engine


Removing the Web Form view engine is easy in MVC. We can remove all the view engines and add only Razor view engine by using Application_Start event of Global.asax.cs file like as:
1. protected void Application_Start() 2. { 3. //Remove All Engine 4. ViewEngines.Engines.Clear(); 5. //Add Razor Engine 6. ViewEngines.Engines.Add(new RazorViewEngine()); 7. ... 8. }

After removing all the view engines and register only Razor view engine, now MVC try to resolve a view by searching the views that match the Razor view engine's naming conventions only as shown in fig.

Note

1. After removing Web Form engine, Razor View Engine will be twice as fast with the Web Form engine.

Inline CSS and Styles with Html Helpers in MVC3 Razor


In Asp.net, we can custom the look and feel of a server controls by using CSS class,id and inline css. Similarly, we can change the style of Html Helpers in MVC razor. I this article, I am going to explain how can change the style of a Html Helpers by using CSS.
CSS Class
1. .inputclass 2. { 3. width:100px; 4. height:25px; 5. }

Apply CSS Class to Html Helpers


Suppose above css class is defined in the external style sheet. Now you want to apply this class to html helpers then we need to add class name by using @class like as :
1. @Html.TextBox("Name", new { @class="inputclass" })

2. @Html.TextBoxFor(model => model.Name, new { @class="inputclass" })

Apply Inline CSS to Html Helpers


We can also add inline css to html helpers by using style like as :
1. @Html.TextBoxFor(model => model.Name, new { style="width:100px;height:25px" }) 2. @Html.TextBox("Name", new { style="width:100px;height:25px" })

Enable jQuery Intellisense support to MVC3 Razor


jQuery intellisense support helps a lot while programming with jQuery. By default Visual Studio doesn't provide us the jQuery intellisense support. We can enable the jQuery intellisense support in Visual Studio with MVC Razor by adding vsdoc.js file to your view like as :
1. @if (false) 2. { 3. <script src="~/Scripts/jquery-1.7.1-vsdoc.js" type="text/javascript"></script> 4. }

The above if-statement prevents the rendering of script tag into the html source code and it used only by the Visual Studio for jQuery intellisense support. To check jQuery intellisense type the $ or $( between your $(document).ready(function() function and you can see the intellisense as shown in fig.

Note

1. In MVC Razor, there is no central place to add the reference to the vsdoc.js file. We need to add this code line to each every view separately to enable the IntelliSense support for jQuery.

Partial View in Asp.net MVC3 Razor


A partial view is like as user control in Asp.Net Web forms that is used for code re-usability. Partial views helps us to reduce code duplication. Hence partial views are reusable views like as Header and Footer views. We can use partial view to display blog comments, product category, social bookmarks buttons, a dynamic ticker, calendar etc.

Creating A Partial View


A partial view has same file extension(.cshtml) as regular view. To create a partial view do right click on shared folder (\Views\Shared) in solution explorer and click on "Add New View" option

and then give the name for partial view and also checked the Create a partial view option as shown in fig.

Note

1. It is best practice to create partial view in the shared folder and partial view name is preceded by "_", but it is not mandatory. The "_" before view name specify that it is a reusable component i.e. partial view.

Rendering Partial View


A partial view is rendered by using the ViewUserControl class that is inherited/derived from the ASP.NET UserControl class. The Partial, RenderPartial, RenderAction helper methods are used to render partial view in mvc3 razor.
<div> @Html.Partial("_Comments") </div> <div> @{Html.RenderPartial("_Comments");} </div>

The main difference between above two methods is that the Partial helper method renders a partial view into a string while RenderPartial method writes directly into the response stream instead of returning a string.

<div> @{Html.RenderAction("_Category","Home");} </div>

Note

1. Partial or RenderPartial methods are used when a model for the page is already populated with all the information. For example in a blog to show an article comment we would like to use Partial or RenderPartial methods since an article information are already populated in the model. 2. RenderAction method is used when some information is need to show on multiple pages. Hence partial view should have its own model. For example to category list of articles on each and every page we would like to use RenderAction method since the list of category is populated by different model.

Render Partial View Using jQuery


Sometimes we need to load a partial view with in a popup on run time like as login box, then we can use jQuery to make an AJAX request and render a Partial View into the popup. In order to load a partial view with in a div we need to do like as:
<script type="text/jscript"> $('#divpopup').load('/shared/_ProductCategory); </script>

When to use ViewModel in mvc3


In asp.net mvc, a controller can pass single object to the corresponding view. This object may be a simple object or a complex object. ViewModel is a complex object that may contain multiple entities or objects from different data models or data source. Basically ViewModel is a class that specify data model used in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

Key Points about View Model


1. ViewModel contain fields that are represented in the view (for LabelFor,EditorFor,DisplayFor helpers) 2. ViewModel can have specific validation rules using data annotations or IDataErrorInfo. 3. ViewModel can have multiple entities or objects from different data models or data source.

ViewModel Example
Designing the model
public class UserLoginModel { [Required(ErrorMessage = "Please enter your username")]

[Display(Name = "User Name")] [MaxLength(50)] public string UserName { get; set; } [Required(ErrorMessage = "Please enter your password")] [Display(Name = "Password")] [MaxLength(50)] public string Password { get; set; } }

Presenting the model in the view


@model MyModels.UserLoginModel @{ ViewBag.Title = "User Login"; Layout = "~/Views/Shared/_Layout.cshtml"; } @using (Html.BeginForm()) { <div class="editor-label"> @Html.LabelFor(m => m.UserName) </div> <div class="editor-field"> @Html.TextBoxFor(m => m.UserName) @Html.ValidationMessageFor(m => m.UserName) </div> <div class="editor-label"> @Html.LabelFor(m => m.Password) </div> <div class="editor-field"> @Html.PasswordFor(m => m.Password) @Html.ValidationMessageFor(m => m.Password) </div> <p> <input type="submit" value="Log In" /> </p> </div> }

Working with Action


public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(UserLoginModel user) { // To acces data using LINQ DataClassesDataContext mobjentity = new DataClassesDataContext(); if (ModelState.IsValid) { try { var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList(); if (q.Count > 0) { return RedirectToAction("MyAccount");

} else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } catch (Exception ex) { } } return View(user); }

Some Tips for using ViewModel


1. In ViewModel put only those fields/data that you want to display on the view/page. 2. Since view reperesents the properties of the ViewModel, hence it is easy for rendering and maintenance. 3. Use a mapper when ViewModel become more complex. In this way, ViewModel help us to organize and manage data in a strongly-typed view with more flexible way than complex objects like models or ViewBag/ViewData objects.

MVC Data Annotations for Model Validation


Data validation is a key aspect for developing web application. In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are availlable to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework orm models. Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.

Data Annotation Validator Attributes DataType


Specify the datatype of a property

DisplayName
specify the display name for a property.

DisplayFormat

specify the display format for a property like different format for Date proerty.

Required
Specify a property as required.

ReqularExpression
validate the value of a property by specified regular expression pattern.

Range
validate the value of a property with in a specified range of values.

StringLength
specify min and max length for a string property.

MaxLength
specify max length for a string property.

Bind
specify fields to include or exclude when adding parameter or form values to model properties.

ScaffoldColumn
specify fields for hiding from editor forms.

Designing the model with Data Annotations


1. using System.ComponentModel; 2. using System.ComponentModel.DataAnnotations; 3. using System.Web.Mvc; 4. namespace Employee.Models 5. { 6. [Bind(Exclude = "AlbumId")] 7. public class Employee 8. { 9. [ScaffoldColumn(false)] 10. public int EmpId { get; set; } 11. [DisplayName("Employee Name")] 12. [Required(ErrorMessage = "Employee Name is required")] 13. [StringLength(100,MinimumLength=3)] 14. public String EmpName { get; set; }

15.

[Required(ErrorMessage = "Employee Address is required")] [StringLength(300)] 16. public string Address { get; set; } 17. [Required(ErrorMessage = "Salary is required")] [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")] 18. public int Salary{ get; set; } 19. [Required(ErrorMessage = "Please enter your email address")] [DataType(DataType.EmailAddress)] 20. [Display(Name = "Email address")] 21. [MaxLength(50)] 22. [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")] 23. public string Email { get; set; } 24. } 25. }

Once we have define validation to the model by using data annotations, these are automatically used by Html Helpers in views. For client side validation to work, please ensure that below two <SCRIPT> tag references are in the view.
1. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 2. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

Presenting the model in the view


1. @model Employee.Models 2. @{ 3. ViewBag.Title = "Employee Details"; 4. Layout = "~/Views/Shared/_Layout.cshtml"; 5. } 6. @using (Html.BeginForm()) 7. { 8. <div class="editor-label"> 9. @Html.LabelFor(m => m.EmpName) 10. </div> 11. <div class="editor-field"> @Html.TextBoxFor(m => m.EmpName) @Html.ValidationMessageFor(m => m.EmpName) 12. </div> 13. <div class="editor-label"> @Html.LabelFor(m => m.Address) 14. </div> 15. <div class="editor-field"> @Html.TextBoxFor(m => m.Address) @Html.ValidationMessageFor(m => m.Address) 16. </div> 17. <div class="editor-label"> @Html.LabelFor(m => m.Salary) 18. </div> 19. <div class="editor-field"> @Html.TextBoxFor(m => m.Salary) @Html.ValidationMessageFor(m => m.Salary) 20. </div> 21. <div class="editor-label"> 22. @Html.LabelFor(m => m.Email) 23. </div>

24.

<div class="editor-field"> @Html.TextBoxFor(m => m.Email) @Html.ValidationMessageFor(m => m.Email) 25. </div> 26. <p> <input type="submit" value="Save" /> 27. </p> 28. </div> 29. }

Setting default submit button in MVC3 razor using jQuery


In Asp.net MVC, sometimes we required to post the form on Enter key press. Asp.net MVC has no default button property like Asp.net. However, we can achieve this functionality by using jQuery in MVC.

Set Form DefaultButton Property using jQuery


1. <script type="text/javascript"> $(document).ready(function (){ $ ("#MyForm").keypress(function (e) { kCode = e.keyCode || e.charCode //for cross browser 2. if (kCode == 13) { var defaultbtn = $(this).attr("DefaultButton"); 3. $("#" + defaultbtn).click(); 4. return false; 5. } 6. }); 7. }); 8. </script> 9. @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { DefaultButton = "SubmitButton", id = "MyForm" })) 10. { 11. @Html.TextBox("txtname") 12. <span>Please Enter value and then press Enter Key</span><br /> 13. <input type="submit" name="btnSubmit" id="SubmitButton" value="Submit" /> 14. }

You might also like