Sunteți pe pagina 1din 20

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 1. 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.

2. 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'

3. 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.

4. 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

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.

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

1. 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'

2. 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.
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. commit TRANSACTION; 14. END TRY 15. BEGIN CATCH 16. rollback TRANSACTION; 17. set @flag=0; 18. END CATCH 19. END

20. 21.

Declare @flag bit --Now Execute this procedure with RECOMPILE option, if you want to recompile its execution plan 22. EXEC usp_InsertEmployee @flag output,2,'Jitendra',15000,'Noida' WITH RECOMPILE 23. if @flag=1 24. print 'Successfully inserted' 25. else 26. 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 Stored Procedure in sql server


Temporary Stored Procedures - SQL Server

supports two types of temporary procedures:

Local temporary procedure Global temporary procedure

Local temporary:

A local temporary procedure is visible only to the connection that created it. Local temporary procedures are automatically dropped at the end of the current session.

Global temporary:

A global temporary procedure is available to all connections. Global temporary procedures are dropped at the end of the last session using the procedure. Usually, this is when the session that created the procedure ends. Temporary procedures named with # and ## can be created by any user.

System stored procedures

are created and stored in the master database and have the sp_

prefix.(or xp_) System stored procedures can be executed from any database without having to qualify the stored procedure name fully using the database name master.

Automatically Executing Stored Procedures

- One or more stored procedures can execute

automatically when SQL Server starts. The stored procedures must be created by the system administrator and executed under the sysadmin fixed server role as a background process.

The procedure(s) cannot have any input parameters.

-------------------------------------------------------

Stored Procedure Basics


Stored procedures in Microsoft SQL Server are similar to procedures in other programming languages in that they can:

Accept input parameters and return multiple values in the form of output parameters to the calling procedure or batch. Contain programming statements that perform operations in the database, including calling other procedures. Return a status value to a calling procedure or batch to indicate success or failure (and the reason for failure).

You can use the Transact-SQL EXECUTE statement to run a stored procedure. Stored procedures are different from functions in that they do not return values in place of their names and they cannot be used directly in an expression. The benefits of using stored procedures in SQL Server rather than Transact-SQL programs stored locally on client computers are:

They are registered at the server. They can have security attributes (such as permissions) and ownership chaining, and certificates can be attached to them. Users can be granted permission to execute a stored procedure without having to have direct permissions on the objects referenced in the procedure.

They can enhance the security of your application. Parameterized stored procedures can help protect your application from SQL Injection attacks. For more information see SQL Injection.

They allow modular programming. You can create the procedure once, and call it any number of times in your program. This can improve the maintainability of your application and allow applications to access the database in a uniform manner.

They are named code allowing for delayed binding. This provides a level of indirection for easy code evolution.

They can reduce network traffic. An operation requiring hundreds of lines of Transact-SQL code can be performed through a single statement that executes the code in a procedure, rather than by sending hundreds of lines of code over the network.

Types of Stored Procedures


There are many types of stored procedures available in Microsoft SQL Server. This topic briefly describes each stored procedure type and includes an example of each.
User-defined Stored Procedures

Stored procedures are modules or routines that encapsulate code for reuse. A stored procedure can take input parameters, return tabular or scalar results and messages to the client, invoke data definition language (DDL) and data manipulation language (DML) statements, and return output parameters. In SQL Server 2008, a stored procedure can be of two types: Transact-SQL or CLR.
Transact-SQL

A Transact-SQL stored procedure is a saved collection of Transact-SQL statements that can take and return user-supplied parameters. For example, a stored procedure might contain the statements needed to insert a new row into one or more tables based on information supplied by the client application. Or, the stored procedure might return data from the database to the client application. For example, an e-commerce Web application might use a stored procedure to return information about specific products based on search criteria specified by the online user.
CLR

A CLR stored procedure is a reference to a Microsoft .NET Framework common language runtime (CLR) method that can take and return user-supplied parameters. They are implemented as public, static methods on a class in a .NET Framework assembly. For more information, see CLR Stored Procedures.
Extended Stored Procedures Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use CLR Integration instead. Extended stored procedures let you create your own external routines in a programming language such as C. Extended stored procedures are DLLs that an instance of Microsoft SQL

Server can dynamically load and run. Extended stored procedures run directly in the address space of an instance of SQL Server and are programmed by using the SQL Server Extended Stored Procedure API.
Note

CLR Integration provides a more robust and secure alternative to writing extended stored procedures.
System Stored Procedures

Many administrative activities in SQL Server are performed through a special kind of procedure known as a system stored procedure. For example, sys.sp_changedbowner is a system stored procedure. System stored procedures are physically stored in the Resource database and have the sp_ prefix. System stored procedures logically appear in the sys schema of every system- and user-defined database. In SQL Server 2008, GRANT, DENY, and REVOKE permissions can be applied to system stored procedures. For a complete list of system stored procedures, see System Stored Procedures (Transact-SQL). SQL Server supports the system stored procedures that provide an interface from SQL Server to external programs for various maintenance activities. These extended stored procedures use the xp_ prefix. For a complete list of extended stored procedures, see General Extended Stored Procedures (Transact-SQL).

Types of stored procedures


The classification of stored procedures is depends on the Where it is Stored. Based on this you can divide it in 4 sections. 1.System stored procedures 2.Local stored procedures 3.Temporary stored procedures 4.Extended stored procedures 1.System Stored Procedures:

System stored procedures are stored in the Master database and are typically named with a sp_ prefix. They can be used to perform variety of tasks to support SQL Server functions that support external application calls for data in the system tables, general system procedures for database administration, and security management functions. For example, you can view the contents of the stored procedure by calling

sp_helptext [StoredProcedure_Name]. There are hundreds of system stored procedures included with SQL Server. For a complete list of system stored procedures, refer to "System Stored Procedures" in SQL Server Books Online. 2.Local stored procedures Local stored procedures are usually stored in a user database and are typically designed to complete tasks in the database in which they reside. While coding these procedures dont use sp_ prefix to you stored procedure it will create a performance bottleneck. The reason is when you can any procedure that is prefixed with sp_ it will first look at in the mater database then comes to the user local database. 3.Temporary stored procedures A temporary stored procedure is all most equivalent to a local stored procedure, but it exists only as long as SQL Server is running or until the connection that created it is not closed. The stored procedure is deleted at connection termination or at server shutdown. This is because temporary stored procedures are stored in the TempDB database. TempDB is re-created when the server is restarted. There are three types of temporary stored procedures: local , global, and stored procedures created directly in TempDB. A local temporary stored procedure always begins with #, and a global temporary stored procedure always begins with ##. The execution scope of a local temporary procedure is limited to the connection that created it. All users who have connections to the database, however, can see the stored procedure in Query Analyzer. There is no chance of name collision between other connections that are creating temporary stored procedures. To ensure uniqueness, SQL Server appends the name of a local temporary stored procedure with a series of underscore characters and a connection number unique to the connection. Privileges cannot be granted to other users for the local temporary stored procedure. When the connection that created the temporary stored procedure is closed, the procedure is deleted from TempDB. Any connection to the database can execute a global temporary stored procedure. This type of procedure must have a unique name, because all connections can execute the procedure and, like all temporary stored procedures, it is created in TempDB. Permission to execute a global temporary stored procedure is automatically granted to the public role and cannot be changed. A global temporary stored procedure is almost as volatile as a local temporary stored procedure. This procedure type is removed when the connection used to create the procedure is closed and any connections currently executing the procedure have completed. Temporary stored procedures created directly in TempDB are different than local and global temporary stored procedures in the following ways:

You can configure permissions for them. They exist even after the connection used to create them is terminated. They aren't removed until SQL Server is shut down. Because this procedure type is created directly in TempDB, it is important to fully qualify the database objects referenced by Transact-SQL commands in the code. For example, you must reference the Authors table, which is owned by dbo in the Pubs database, as pubs.dbo.authors. --create a local temporary stored procedure. CREATE PROCEDURE #tempShashi AS SELECT * from [pubs].[dbo].[shashi] --create a global temporary stored procedure. CREATE PROCEDURE ##tempShashi AS SELECT * from [pubs].[dbo].[shasi] --create a temporary stored procedure that is local to tempdb. CREATE PROCEDURE directtemp AS SELECT * from [pubs].[dbo].[shashi] 4.Extended Stored Procedures An extended stored procedure uses an external program, compiled as a 32-bit dynamic link library (DLL), to expand the capabilities of a stored procedure. A number of system stored procedures are also classified as extended stored procedures. For example, the xp_sendmail program, which sends a message and a query result set attachment to the specified e-mail recipients, is both a system stored procedure and an extended stored procedure. Most extended stored procedures use the xp_ prefix as a naming convention. However, there are some extended stored procedures that use the sp_ prefix, and there are some system stored procedures that are not extended and use the xp_ prefix. Therefore, you cannot depend on naming conventions to identify system stored procedures and extended stored procedures. Use the OBJECTPROPERTY function to determine whether a stored procedure is extended or not. OBJECTPROPERTY returns a value of 1 for IsExtendedProc, indicating an extended stored procedure, or returns a value of 0, indicating a stored procedure that is not extended. USE Master SELECT OBJECTPROPERTY(object_id('xp_sendmail'), 'IsExtendedProc')

Difference between Sql server 2005 and 2008


There are some differences between both.

Sr No SQL Server 2005 1 2 3 4 5 6 7 XML datatype is introduced. Can not encrypt the entire database. No table datatype is included. SSIS is started using. CMS is not available. PBM is not available

SQL Server 2008 XML datatype is used. Can encrypt the entire database introduced in 2008. Table datatype introduced. SSIS avails in this version. Central Management Server(CMS) is Introduced. Policy based management(PBM) server is Introduced.

Datetime is used for both date and time. Date and time are seperately used for date and time

Find the execution time of a stored procedure


The best way is to use SQL profiler. Just choose the required events.Else if you dont have the permission to access SQL Profiler or want to determine that programatically, then try:
DECLARE @StartDate datetime, @EndDate datetime SET @StartDate = getdate() /* --Exec your stored procedure code here-*/ SET @EndDate = getdate() SELECT datediff(ms,@StartDate, @EndDate) AS 'Milliseconds'

Difference between stored procedure and Functions


Stored procedures: 1) 2) 3) 4) 5) 6) 7) have to use EXEC or EXECUTE return output parameter can create table but won't return Table Variables you cannot join SP Can be used to change server configuration. Can be used with XML FOR Clause can have transaction within SP

8) Procedures can be used for performing business logic

9) Sp takes input, output parameters, 10) Sp cannot be called directly into DML statements 11) PROCEDURE may return one or more values through parameters or may not return at all 12) Procedure can return multiple values (max 1024). 13) Stored procedure returns always integer value by default zero. 14) Stored procedure is precompiled execution plan 15) Procedure cannot be used in SQL queries

Functions 1) 2) 3) 4) 5) 6) Can be used with Select statement Not returning output parameter but returns Table variables We can join UDF Cannot be used to change server configuration. Cannot be used with XML FOR clause cannot have transaction within function

7) Functions are used for computations 8) Function takes only input parameters. 9) Functions can be called directly into DML statements. 10) A FUNCTION is always returns a value using the return statement 11) A Function returns 1 value only. 12) Whereas function returns type could be scalar or table or table values 13) A function can call directly by SQL statement like select func_name from dual 14) A Function can be used in the SQL Queries

DIFFERENCE BETWEEN DROP AND TRUNCATE


1. DROP WILL REMOVE THE OBJECT WHERE ARE DELETE WILL REMOVE ONLY THE DATA DELETE WILL DELETE EACH RECORD 2. NO LOGGING IN TRUNCATE ... LOGGING WILL HAPPEN IN DROP STATEMENT

Difference between Truncate and Delete


1. TRUNCATE WILL DELETE THE ENTIRE TABLE @ A STRETCH DELETE WILL DELETE EACH RECORD 2. NO LOGGING IN TRUNCATE ... LOGGING DELETE 3. PROCESS IS TOO FAST AND WE CAN RECOVER THE DATA IN TRUNCATE

Types of Stored procedure

System Stored Procedures System Stored procedures are nothing but in-built stored procedures which deals which the internal metadata of the SQL Server. There is bunch of system stored procedure, for more details refer to MSDN or link : http://msdn.microsoft.com/en-us/library/ms187961.aspx

EX. sp_renamedb. This system procedure helps to rename the database name.

User-defined Store Procedures User Defined Store procedures are deals with the relational data in the database, created by the end-user. o Simple Stored procedure In this type of SP, there are no In / Out parameter involve. Stored procedure with simple SQL Query with / without JOINS. CREATE PROCEDURE dbo.usp_GetPersons() BEGIN SET NOCOUNT ON SELECT * FROM dbo.Persons END

Parameterized Stored procedure In this type of SP, there are In / Out / Both parameter involve. CREATE PROCEDURE dbo.usp_GetPersons( @PersonKey ) BEGIN SET NOCOUNT ON SELECT * FROM dbo.Persons WHERE PersonKey = @PersoneID END

S-ar putea să vă placă și