Counter of Festivals

Ashok Blog for SQL Learners and Beginners and Experts

Thursday, 29 November 2012

Difference between Stored Procedure and Function in SQL Server and Primary key and Unique Key and Foreign Key

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.


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. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
  5. We can go for Transaction Management in Procedure whereas we can't go in Function.

Difference between Primary Key and 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.


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 Foreign key do not automatically create an index, clustered on non-clustered. You can manually create an index on foreign key
   
We can have only one Primary key in a table. We can have more than one foreign key in a table.

No comments:

Post a Comment