Let's play with Trigger

A trigger is a database object which is attached to table and similar to stored procedure. The main difference between triggers and stored procedures is:-
1- Triggers do not accept parameter whereas procedure can.
2- A trigger is executed implicitly and to execute a procedure, it has to be explicitly called by user.

How to apply database triggers
A trigger has three basic parts:-
1- A triggering statement
2- A trigger restriction
3- A trigger action

Triggering Statement:-
It is a sql statement that causes a trigger to be fired. It can be insert, update or delete statement for a specific table.

Trigger restriction:-
A trigger restriction specifies a logical expression that must be TRUE for the trigger to fire. A trigger restriction specifies using WHEN clause.

Trigger Action:-
A trigger action code is executed when a triggering statement is encountered and any trigger restirction evaluates to true.

Type of triggers
Row Triggers
A row trigger is fired each time a row in the table is affected by the triggering statement. For example, if an update statement updates multiple rows of a table, a row trigger is fired once for each row affected by the update statement.

Statement Triggers
A statement trigger is fired once on behalf of the triggering statement, independent of the number of rows the triggering statement affects. Statement triggers should be used when a triggering statement affects rows in a table but the processing required is completely independent of the number of rows affected.

Before V/s After triggers
BEFORE triggers executes the trigger action before the triggering statement. These types of triggers are commonly used in the following situations:-

a) BEFORE triggers are used when the trigger action should determine wheather or not the triggering statement should be allowed to complete.

b) BEFORE triggers are used to derive specifc column values before completing triggering insert or update statement.

AFTER trigger executes the trigger action after the triggering statement is executed. These types of triggers are commonly used in the following situations:-

a) AFTER triggers are used when you want the triggering statement to complete before executing the trigger action.

b) If a BEFORE trigger is already present, an AFTER trigger can perform different actions on the same triggering statement.

The following example demonstrate how to create trigger that displayes the current system time when a row is inserted into the table.

SET NOCOUNT ON
CREATE TABLE Source (Sou_ID int IDENTITY, Sou_Desc varchar(10))
GO
CREATE TRIGGER tr_Source_INSERT
ON Source
FOR INSERT
AS
PRINT GETDATE()
GO
INSERT Source (Sou_Desc) VALUES ('Test 1')
-- Results --
Apr 17 2010 9:56AM

When to use triggers
We should use trigger when we need to perform a certain action as a result of an INSERT, UPDATE or DELETE is used.

CREATE TABLE Orders (Ord_ID int IDENTITY, Ord_Priority varchar(10))
GO
CREATE TRIGGER tr_Orders_INSERT
ON Orders
FOR INSERT
AS
IF (SELECT COUNT(*) FROM inserted WHERE Ord_Priority = 'High') = 1
BEGIN
PRINT 'Email Code Goes Here'
END
GO
INSERT Orders (Ord_Priority) VALUES ('High')
-- Results --
Email Code Goes Here

how to know database size using query

select * from sys.dm_db_file_space_usage

or you can try...

exec sp_spaceused

Stored Proceures Basics

Stored procedure are compiled SQL code stored in database. Calling stored procedure as opposed to sending over query strings improves the performance of a web application. Not only is there less network traffic since only short commands are sent instead of long query stings, but the execution of the actually code itself also improves. The reason is because a stored procedure is already compiled ahead of time. Stored procedures are also cached by SQL Server when they are run to speed things up for subsequent calls.

Other than performance, stored procedures are also helpful because they provide another layer of abstraction for your web application. For instance, you can change a query in a stored procedure and get different results without having to recompile your objects. Using stored procedures also makes your objects cleaner, and SQL Server’s convenient backup tool makes it easy to back them up.

There are various options that can be used to create stored procedures. In these next few topics we will discuss creating a simple stored procedure to more advanced options that can be used when creating stored procedures.

Creating a simple stored procedure
To create a stored procedure to do this the code would look like this:

CREATE PROCEDURE dbo.USP_projName_modulename
AS SELECT * FROM dbo.tblName
GO

To call the procedure to return the contents from the table specified, the code would be:

EXEC
USP_projName_modulename
--or just simply
USP_projName_modulename

When creating a stored procedure you can either use CREATE PROCEDURE or CREATE PROC. After the stored procedure name you need to use the keyword "AS" and then the rest is just the regular SQL code that you would normally execute.

One thing to note is that you cannot use the keyword "GO" in the stored procedure. Once the SQL Server compiler sees "GO" it assumes it is the end of the batch.

Stored procedure with parameters
The real power of stored procedures is the ability to pass parameters and have the stored procedure handle the differing requests that are made.

In this example we will query the address table from the master database, but instead of getting back all records we will limit it to just a particular city. This example assumes there will be an exact match on the City value that is passed.

CREATE PROCEDURE dbo.USP_abc_GetMembersBasedOnCity
(
@City nvarchar(30)
)
AS
SELECT *
FROM dbo.address
WHERE City = @City
GO

To call this stored procedure we would execute it as follows:

EXEC USP_abc_GetMembersBasedOnCity @City = 'Delhi'
In most cases it is always a good practice to pass in all parameter values, but sometimes it is not possible. So in this example we use the NULL option to allow you to not pass in a parameter value. If we create and run this stored procedure as is it will not return any data, because it is looking for any City values that equal NULL.

CREATE PROCEDURE dbo.USP_abc_GetMembersBasedOnCity @City nvarchar(30) = NULL
AS
SELECT *
FROM dbo.address
WHERE City = @City
GO

We could change this stored procedure and use the ISNULL function to get around this. So if a value is passed it will use the value to narrow the result set and if a value is not passed it will return all records.

CREATE PROCEDURE dbo.USP_abc_GetMembersBasedOnCity @City nvarchar(30) = NULL
AS
SELECT *
FROM dbo.address
WHERE City = ISNULL(@City,City)
GO

Above we discussed how to pass parameters inside SPs, but there is one other option, to pass parameter values backout from SP.

Setting up output paramters for a stored procedure is basically the same as setting up input parameters, the only difference is that you use the OUTPUT clause after the parameter name to specify that it should return a value. The output clause can be specified by either using the keyword "OUTPUT" or just "OUT".

CREATE PROCEDURE dbo.USP_abc_GetMembersBasedOnCity (
@City nvarchar(30),
@AddressCount int OUTPUT
)
AS
SELECT @AddressCount = count(*)
FROM address
WHERE City = @City
Go

To call this stored procedure we would execute it as follows. First we are going to declare a variable, execute the stored procedure and then select the returned valued.

DECLARE @AddressCount int
EXEC USP_abc_GetMembersBasedOnCity @City = 'Calgary', @AddressCount = @AddressCount OUTPUT
SELECT @AddressCount

Using try catch in SQL Server stored procedures

Doing error handling in SQL Server has not always been the easiest thing, so this option definitely makes it much easier to code for and handle errors.

If you are not familiar with the Try...Catch paradigm it is basically two blocks of code with your stored procedures that lets you execute some code, this is the Try section and if there are errors they are handled in the Catch section.

Let's take a look at an example of how this can be done. As you can see we are using a basic SELECT statement that is contained within the TRY section, but for some reason if this fails it will run the code in the CATCH section and return the error information.

CREATE PROCEDURE uspTryCatchTest
AS
BEGIN TRY
SELECT 1/0
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;
END CATCH

Naming conventions for SQL Server stored procedures

1- One of the things you do not want to use as a standard is "sp_". This is a standard naming convention that is used in the master database. If you do not specify the database where the object is, SQL Server will first search the master database to see if the object exists there and then it will search the user database. So avoid using this as a naming convention.

I liked to first give the action that the stored procedure takes and then give it a name representing the object it will affect.

So based on the actions that you may take with a stored procedure, you may use:
* Insert
* Delete
* Update
* Select
* Get
* Validate
* etc...
So here are a few examples:
* USP_projName_personDelete
* USP_projName_personGetData

Reducing amount of network data for SQL Server stored procedures

There are many tricks that can be used when you write T-SQL code. One of these is to reduce the amount of network data for each statement that occurs within your stored procedures. Every time a SQL statement is executed it returns the number of rows that were affected. By using "SET NOCOUNT ON" within your stored procedure you can shut off these messages and reduce some of the traffic.

Not using SET NOCOUNT ON

CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
GO

The messages that are returned would be similar to this:

20 rows affected

Using SET NOCOUNT ON

-- using SET NOCOUNT ON
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SET NOCOUNT ON
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
GO

The messages that are returned would be similar to this:

Command(s) completed successfully.

Using SET NOCOUNT ON and @@ROWCOUNT
-- not using SET NOCOUNT ON
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SET NOCOUNT ON
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
PRINT @@ROWCOUNT
GO

The messages that are returned would be similar to this:

20

Dropping Single Stored Procedure

To drop a single stored procedure you use the DROP PROCEDURE or DROP PROC command as follows.
DROP PROCEDURE uspGetAddress

Dropping Multiple Stored Procedures
DROP PROCEDURE uspGetAddress, uspInsertAddress, uspDeleteAddress
GO