Cannot grant, deny, or revoke permissions to sa, dbo, entity owner, information_schema, sys, or yourself

When you try to give GRANT EXECUTE permission to some SQL Objects then smetimes you might encounter below issue:-

Cannot grant, deny, or revoke permissions to sa, dbo, entity owner, information_schema, sys, or yourself

Resolutions:-
As per the comments, if you're already the db owner of that database, than you don't need to grant any permission for the db.

Now, in order to find out what specific permissions you have, you can use the following queries:

USE AdventureWorks2008R2;
SELECT * FROM fn_my_permissions (NULL, 'DATABASE');
GO

Meaning of SET ANSI_NULL ON

When create or alter SQL objects in Query Analyzer, We used below commands before the objects:-
SET QUOTED_IDENTIFIER ON
GOSET ANSI_NULLS ON
GO


ANSI NULL ON/OFF:
This option specifies the setting for ANSI NULL comparisons. When this is on, any query that compares a value with a null returns a 0. When off, any query that compares a value with a null returns a null value.
When
SET ANSI_NULL ON
it means ISO Standard is being followed.
= and <> should not be used for null comparison.

If you want to use = or <> for null comparison use
SET ANSI_NULL OFF
QUOTED IDENTIFIER ON/OFF:
This options specifies the setting for usage of double quotation. When this is on, double quotation mark is used as part of the SQL Server identifier (object name). This can be useful in situations in which identifiers are also SQL Server reserved words.
It specifies how SQL Server treats the data that is defined in Single Quotes and Double Quotes. When it is set to ON any character set that is defined in the double quotes “” is treated as a T-SQL Identifier (Table Name, Proc Name, Column Name….etc) and the T-SQL rules for naming identifiers will not be applicable to it. And any character set that is defined in the Single Quotes ‘’ is treated as a literal.
A smart way towards Indexes in SQL 

Indexes are special lookup tables that the database search engine use to speed up data retrieval. This article focuses on how SQL Server uses indexes to read and write data. Data is arranged in SQL Server in the form of extents and pages. Each extent is of size 64 KB, having 8 pages of 8 KB sizes. An extent may have data from multiple or same table, but each page holds data from a single table only. Logically, data  is stored in record sets in tables. A table is nothing but a collection of record sets; by default, rows are stored in the form of heaps unless a clustered index has been defined on the table, in which case, record sets are sorted and stored on the clustered index. The heaps structure is a simple arrangement where the inserted record is stored in the next available space on the table page. 

Indexes are arranged in the form of a B-Tree where the leaf node holds the data or a pointer to the data. Since the stored data is in a sorted order, indexes precisely know which record is sitting where. Hence an index optimizes and enhances the data retrieval immensely.

We have two types of Indexes in SQL Server:-

1- Clustered indexes
2- Non-Clustered indexes

Clustered Indexes

A clustered index is something that reorganizes the way records in the table are physically stored. Therefore a table can have only one clustered index. The leaf nodes of a clustered index contain the data pages, by which I mean the key-value pair in the clustered index has the index key and the actual data value. Also remember, a clustered index will be created on a table by default the moment a primary key is created on the table.

Syntax for creating the clustered index is:-

CREATE CLUSTERED INDEX CI_ID ON Sales(ID)

Non Clustered Indexes

A non-clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non-clustered index does not consist of the data pages but a pointer to it.

Important points about Indexes

1- SQL Server allows at most one clustered index in any version. As far as non-clustered indexes are concerned, Version 2005 allows 249 of them to be created while version 2008 allows 999 non-clustered indexes.
2- When we create a primary key, by default clustered index is created on that column.
3- We can use DTA to know the recommended index.

Interview Question

Q:- Once we declare a primary key, a clustered index is created on the column by default; what if I wish to create a clustered index and a primary key on two different columns? Is it possible?

A:- It is very much possible to have two different columns as primary key and clustered indexes. But remember, if I create a Primary Key on a table first, a CI will also be created. Now, in case I need them on two different columns, drop the Primary Key constraint and the CI shall automatically vanish. Now create a CI on column A and declare column B as Primary Key, and column B will have a NCI created by default on it instead of a CI. This way, we can have two columns as Primary Key and CI declared on them.

Q:- What are the disadvantages of index?

A:- 1-Use of intexes slow down Data modification operations (such as INSERT, UPDATE, DELETE).
         2- Every time data changes in the table, all the indexes need to be updated.
         3- Indexes need disk space, the more indexes you have, more disk space is used.
 

Q:- Explain the difference between clustered and non-clustered index.

A:- A clustered index reorders the way records are stored. A non clustered index is in which the logical order of the index does not match the physical stored order of the rows on disk. A clustered index is must faster because the index entries are actually data records. There can be just one clustered index per table while there can be up to 249 non clustered indexes

Q:- Define Clustered and Non-Clustered Index

A:- Clustered index exists as sorted row on disk.
Clustered index re-orders the table record.
Clustered index contains record in the leaf level of the B-tree.
There can be only one Clustered index possible in a table.

Non-clustered is the index in which logical order doesn’t match with physical order of stored data on disk.
Non-clustered index contains index key to the table records in the leaf level. 
There can be one or more Non-clustered indexes in a table. 

Q:- What is Unique Index?

A:- Unique index is the index that is applied to any column of unique value. 
A unique index can also be applied to a group of columns. 

Q:- Explain the 'Fillfactor' concept in Indexes. 

A:- The fill factor option is provided for smoothening index data storage and performance. 
The percentage of space on each leaf level page to be filled with data is determined by the fill factor value When an index is created. This reserves a percentage of free space for future growth

Q:- What is it unwise to create wide clustered index keys? 

A:- A clustered index is a good choice for searching over a range of values. After an indexed row is found, the remaining rows being adjacent to it can be found easily. However, using wide keys with clustered indexes is not wise because these keys are also used by the non-clustered indexes for look ups and are also stored in every non-clustered index leaf entry 

Q:- What is full-text indexing?

A:- Full text indexes are stored in the file system and are administered through the database.
Only one full-text index is allowed for one table. They are grouped within the same database in full-text catalogs and are created, managed and dropped using wizards or stored procedures 

Q:- What are the different types of indexes?

A:- 
  • Clustered: It sorts and stores the data row of the table or view in order based on the index key.
  • Non clustered: it can be defined on a table or view with clustered index or on a heap. Each row contains the key and row locator.
  • Unique: ensures that the index key is unique
  • Spatial: These indexes are usually used for spatial objects of geometry
  • Filtered: It is an optimized non clustered index used for covering queries of well defined data 


 Roll Up Multiple Rows into a single rows and column

 By: Ashutosh Dixit        Date: 01 May 2013




 Delete duplicate records from a table

 By: Ashutosh Dixit        Date: 25 April 2013

Sql Server Basic - Contents

Day 1- Introduction to MS SQL Server
Day 2- SQL Server installation
Day 3- What is RDBMS?
Day 4- Normalization
Day 5- De-Normalization
Day 6- ACID Property
Day 7- Variables and Data Types
Day 8- Writing basic queries
Day 9- Writing Advance Queries
Day 10- SQL Server Constraints
Day 11- Aggregate Functions
Day 12- Sub Queries
Day 13- Joins
Day 14- Indexes
Day 15- Views
Day 16- Stored Procedures
Day 17- Triggers
Day 18- User Defined functions
Day 19- Linked Server
Day 20- Cursor
Day 21- Collation
Day 22- Transactions
Day 23- Privileges
Day 24- Sql Server Logins
Day 25- Sql Server Roles
Day 26- Sql Server BackUp
Day 27- Why Temporary Table
Day 28- Why Table variable
Day 29- Some useful queries
Day 30- Useful tips

Day 1- Introduction to MS SQL Server

Microsoft SQL Server is a relational database management system which is designed to run from single desktop machine to multiprocessor huge servers. Basically SQL Server is used to store the large data of websites as well as of CRMs.

SQL Server uses a type of database called a relational database. In relational databases, data is organized into tables.Tables are organized by grouping data about the same subject and contain columns and rows of information.

As you saw, a relational database is composed of different types of objects. The following are some of the more common objects:

1- Tables are the objects that contain the data types and actual raw data.

2- Columns are the parts of the tables holding the data.

3- Data types are the base storage type of your data.

4- Stored procedures are like macros in that SQL code that can be written and stored under a name.

5- User defined functions are transact SQL code thats very similar to stored procedures.

6- Triggers are stored procedures that activate either before or after data is added, modified or deleted from the database.

7- Views are basically queries stored in the database that can reference one or many tables.

8- Index can help organize data so that queries run faster.

9- Primary keys are essential to relational database. They enforce uniqueness among rows, providing a way to uniquely identify
every item you want to store.

10- Foreign key are one or more columns that reference the primary keys or unique constraints of other tables.

All above mentioned objects are described in brief. There are other objects as well which will be described in details among with above mentioned objects in this tutorial latter.

In the next chapter we will learn how to install SQL Server onto your machine, in a network environment.

Previous
Index
Next

RDBMS Basics

RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, Oracle, MySQL, and Microsoft Access.

In Simple word RDBMS is a database management system that is based on the relational model as introduced by E. F. Codd.

Generally, these databases will be more complex than the text file/spreadsheet example in the previous lesson.
In fact, most of today's database systems are referred to as a RDBMS, because of their ability to store related data across multiple tables.

Some of the more popular relational database management systems include:

* Microsoft Access
* Microsoft SQL Server
* MySQL
* Oracle

In Short below are the basics of RDBMS:-

RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd.

The data in RDBMS is stored in database objects called tables. The table is a collection of related data entries and it consists of columns and rows.

Every table is broken up into smaller entities called fields.

A record, also called a row of data, is each individual entry that exists in a table. A column is a vertical entity in a table that contains all information associated with a specific field in a table.

Useful Queries (Group By example)

Find out the results on the basis of grouping

Sometimes we got the requirement where we have to group the results on the basis of a column. Let me explain you steps by step:-

Step 1: Create a table first


CREATE TABLE groupingExample(
id INT IDENTITY (1, 1)
,exc_idn INT
,lot_nbr VARCHAR(20)
)
GO

Step 2: Insert the sample record into this table


INSERT INTO groupingExample (exc_idn, lot_nbr)
SELECT 5760441, 'F0389441'
UNION ALL
SELECT 5760441, 'F0389541'
UNION ALL
SELECT 5760517, 'F0367191'
UNION ALL
SELECT 5760517, 'F0384651'
UNION ALL
SELECT 5760523, 'F0367191'
UNION ALL
SELECT 5760523, 'F0384651'
UNION ALL
SELECT 5760643, 'F0366961'
UNION ALL
SELECT 5760885, 'F0365977'
UNION ALL
SELECT 5764109, 'F0312698'
UNION ALL
SELECT 5764109, 'F0312671'
GO

Step 3: Now write a query which will give that each exc_idn contain how many lot_nbr in this table. Let's do it in this way

SELECT exc_idn, COUNT(lot_nbr) COUN FROM groupingExample GROUP BY exc_idn

And the output would be something like

exc_idn         COUN      

5760441         2
5760517         2
5760523         2
5760643         1
5760885         1
5764109         2

You can also use the order by clause with the above query like

SELECT exc_idn, COUNT(lot_nbr) COUNT FROM groupingExample GROUP BY exc_idn order by 2 desc


Thanks.


Roll Up Multiple Rows into a single rows and column.

Sometimes we got a requirement where we have to bind the multiple rows into a single row and column. For example the requirement is like, we have a table called tblCategory (parent table) and another table tblBrands (child table) which stored the data as following:-

tblCategory                                    

tblBrands
                                                         


And we want the result display as:
                                             

Now we have to find out the best way to achieve this requirement. 

The solutions which we are going to explore will use two SQL commands STUFF and FOR XML. We will explain about these commands later in this tutorial.

As all of us will be aware about INNER JOIN so first lets write it in very simple manner:-

SELECT   c.cat_name
,b.brand_nme
FROM tblCategory c
JOIN tblBrands b ON b.cat_id = c.id
ORDER BY 1, 2

And we will get the results in following way



Lets take one step ahead and use FOR XML PATH option which will return the result as XML string and will put all the data into one row and column. 

SELECT   c.cat_name
,b.brand_nme
FROM tblCategory c
JOIN tblBrands b ON b.cat_id = c.id
ORDER BY 1, 2
FOR XML PATH ('')

And here the result will appear as 



Now try to convert the join into part of the select statement

SELECT  c.cat_name
,(SELECT '; '+b.brand_nme FROM tblBrands b WHERE b.cat_id = c.id FOR XML PATH('')) [Section]
FROM tblCategory c
ORDER BY 1

The result would be like


Now finally use the STUFF command to fulfill our requirement

SELECT  c.cat_name
,STUFF((SELECT '; '+b.brand_nme FROM tblBrands b WHERE b.cat_id = c.id FOR XML PATH('')), 1, 1, '') [Section]
FROM tblCategory c
GROUP BY c.cat_name, c.id
ORDER BY 1


And here we go!





There might be other best options to achieve this requirement but this one I used during my project. Other best solutions and comments are also most welcome!                                        

Useful queries (inner join by example)

Find out the common records from two tables

Sometimes we need to figure out the common records from two tables. Here we figure it out step by step:-

Step 1 - Create two tables as below:


CREATE TABLE tblA(
id INT
,name VARCHAR(20)
)
GO


CREATE TABLE tblB(
id INT
,name VARCHAR(20)
)
GO

Step 2 - Now insert some records into these two table as below:


INSERT INTO tblA VALUES(1, 'Alok')
INSERT INTO tblA VALUES(2, 'Ashu')
INSERT INTO tblA VALUES(3, 'Manu')
INSERT INTO tblA VALUES(4, 'Ravi')
INSERT INTO tblA VALUES(5, 'Baby')
GO


INSERT INTO tblB VALUES(1, 'Alok')
INSERT INTO tblB VALUES(2, 'Ashu')
INSERT INTO tblB VALUES(3, 'Manu')
INSERT INTO tblB VALUES(4, 'Ravi')
INSERT INTO tblB VALUES(6, 'Raju')
GO

Step 3 - Now write the query to find out the common records:


SELECT a1.id, a1.name, a2.id, a2.name
FROM tblA a1
JOIN tblB a2 ON a1.id = a2.id
GO

And the result would be like this


id      name       id     name
1       Alok        1        Alok
2       Ashu        2       Ashu
3       Manu       3       Manu
4       Ravi         4       Ravi



Thanks.





Useful queries (self join by example)

How to find out the Manager of respective employee from a single table (Self Join by example)

Suppose here is a table called employee:-

empId       name           mngrId 
   1            Alok                 2
   2            Ashu                 3
   3            Manu                4
   4            Ravi                  5
   5            Baby                 1

Now the requirement is to find out the manager of each employee. Lets do it step by step:-

Step 1- Create a table with following statement:


CREATE TABLE employee(
empid INT
,name VARCHAR(20)
,mngrId INT
)
GO

Step 2- Insert the data into employee table:


INSERT INTO employee SELECT 1, 'Alok', 2
INSERT INTO employee SELECT 2, 'Ashu', 3
INSERT INTO employee SELECT 3, 'Manu', 4
INSERT INTO employee SELECT 4, 'Ravi', 5
INSERT INTO employee SELECT 5, 'Baby', 1
GO

Step 3- Write the query to fetch the required result:


SELECT e1.name empName, e2.name mngrName
FROM employee e1
      JOIN employee e2 ON e1.mngrId = e2.empid
GO

Thanks.






GET SERVER VERSION

GET SERVER VERSION - 

SELECT @@VERSION VersionInfo
GO

Simple approach to encrype and decrype data in SQL Server 2005 and +

When I want to use SQL encryption, what I really want encrypt columns of data. SQL Server doesn't offer an "encryption" attribute for columns, so what we should do is to manually encrypt the data on insert/update and then decrypt the data when selecting. Let's see how it works:-

CREATE TABLE test
(
ID INT not null IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
normalText VARCHAR(16) not null,
EncryptedText VARBINARY(68) not null
);
GO
--passphrase approach

DECLARE @s VARCHAR(16);
SET @s = 'Ashutosh';
INSERT test(normalText, EncryptedText) values (@s, EncryptByPassPhrase('MyPassPhrase', @s));
GO

--verify we can decrypt data
SELECT ID, normalText,
cast(DecryptByPassPhrase('MyPassPhrase', EncryptedText) as varchar(16)) as "Decrypted",
EncryptedText --just to verify the data really is encrypted
FROM test;
GO

The simplest way to encrypt/decrypt data is with the EncryptByPassphrase() and DecryptByPassPhrase() functions.

Normalization Basics

In this article, we will discuss in details about normalization. Generally asked questions is - What is normalization? Why we should use normalization? Is our database is normalized?

Basically, Normalization is the process of organizing data into database efficiently. There are two goals of normalization:-
1- Eliminating redundant data
2- Ensuring data dependencies make sense

The database community has developed a series of guidelines for ensuring that data is normalized in database. These series are
referred to as normal forms and are numbered from 1NF to 5NF. In general practice, we used 1NF, 2NF and 3NF. Occasional we use 4NF. 5NF is very rarely seen and is out of scope this article.

First Normal Form (1NF)
First normal form (1NF) sets the very basic rules for an organized database:

* Eliminate duplicate columns from the same table.
* Create separate tables for each group of related data and identify each row with a unique column or set of columns

Second Normal Form (2NF)
Second normal form (2NF) further addresses the concept of removing duplicative data:

* Meet all the requirements of the first normal form.
* Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
* Create relationships between these new tables and their predecessors through the use of foreign keys.

Third Normal Form (3NF)
Third normal form (3NF) goes one large step further:

* Meet all the requirements of the second normal form.
* Remove columns that are not dependent upon the primary key.

Fourth Normal Form (4NF)
Finally, fourth normal form (4NF) has one additional requirement:

* Meet all the requirements of the third normal form.
* A relation is in 4NF if it has no multi-valued dependencies.

Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database.

I think its enough for this article. I will update this article with practical example soon.

Feature of SQL Server 2008

Most popular question asked by database developers is why we migrated to SQL Server 2008? What is the new feature in 2008 which was not in 2005?

Here is brief summary of the differences and I will try to explain why SQL Server 2008 is rocking.

1- Plug is model for SSMS:- SSMS 2005 also had a plug in model but this was not published.

2- Inline variable assignment:-

Instead of:

DECLARE @myVar int
SET @myVar = 5

you can do it in one line:

DECLARE @myVar int = 5

3- Filtered index:- it allows you to create an index while specifying what rows are not to be in the index. For example, index all rows where Status != null.

4- Intellisense:- in the SQL Server Management Studio (SSMS). This has been previously possible in SQL Server 2000 and 2005 with Intellisense use of 3rd party add-ins like SQL Prompt ($195). But these tools are a horrible hack at best.

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

Sql Server Views

Sql Server Views

Creates a virtual table that represents the data in one or more tables in an alternative way. CREATE VIEW must be the first statement in a query batch.

schema_name

Is the name of the schema to which the view belongs.

view_name

Is the name of the view.

Column

Is the name to be used for a column in a view. A column name is required only when a column is derived from an arithmetic expression, a function, or a constant.

AS

Specifies the actions the view is to perform.

select_statement

Is the SELECT statement that defines the view. The statement can use more than one table and other views. In an indexed view definition, the SELECT statement must be a single table statement or a multitable JOIN with optional aggregation.

The SELECT clauses in a view definition cannot include the following:

  • COMPUTE or COMPUTE BY clauses
  • An ORDER BY clause, unless there is also a TOP clause in the select list of the SELECT statement
  • The INTO keyword
  • The OPTION clause
  • A reference to a temporary table or a table variable.

Syntax

CREATE VIEW view_name
[(column_name[,column_name]….)]
[WITH ENCRYPTION]
AS select_statement [WITH CHECK OPTION]

CREATE VIEW hiredate_view

AS

SELECT p.FirstName, p.LastName, e.BusinessEntityID, e.HireDate

FROM HumanResources.Employee e

JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID ;

GO

ENCRYPTION

Encrypts the entries in sys.syscomments that contain the text of the CREATE VIEW statement. Using WITH ENCRYPTION prevents the view from being published as part of SQL Server replication.

CREATE VIEW Purchasing.PurchaseOrderReject

WITH ENCRYPTION

AS

SELECT PurchaseOrderID, ReceivedQty, RejectedQty,

RejectedQty / ReceivedQty AS RejectRatio, DueDate

FROM Purchasing.PurchaseOrderDetail

WHERE RejectedQty / ReceivedQty > 0

AND DueDate > CONVERT(DATETIME,'20010630',101) ;

GO

SCHEMABINDING

Binds the view to the schema of the underlying table or tables. When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified. When you use SCHEMABINDING, the select_statement must include the two-part names - (schema.object) of tables, views, or user-defined functions that are referenced. All referenced objects must be in the same database.

If a view is not created with the SCHEMABINDING clause, sp_refreshview should be run when changes are made to the objects underlying the view that affect the definition of the view. Otherwise, the view might produce unexpected results when it is queried.

CREATE VIEW vwSample
With SCHEMABINDING
As
SELECT

CustomerID,
CompanyName,
ContactName

FROM DBO.CUSTOMERS -- Two part name [ownername.objectname]
GO

When a view is created, information about the view is stored in the following catalog views: sys.views, sys.columns, and sys.sql_expression_dependencies. The text of the CREATE VIEW statement is stored in the sys.sql_modules catalog view.

Updatable Views

You can modify the data of an underlying base table through a view, as long as the following conditions are true:

  • Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.
  • The columns being modified in the view must directly reference the underlying data in the table columns. The columns cannot be derived in any other way, such as through the following:

  • An aggregate function: AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR, and VARP.
  • A computation. The column cannot be computed from an expression that uses other columns. Columns that are formed by using the set operators UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT amount to a computation and are also not updatable.

The columns being modified are not affected by GROUP BY, HAVING, or DISTINCT clauses.

  • TOP is not used anywhere in the select_statement of the view together with the WITH CHECK OPTION clause.

INSTEAD OF Triggers

INSTEAD OF triggers can be created on a view to make a view updatable. The INSTEAD OF trigger is executed instead of the data modification statement on which the trigger is defined. This trigger lets the user specify the set of actions that must happen to process the data modification statement. Therefore, if an INSTEAD OF trigger exists for a view on a specific data modification statement (INSERT, UPDATE, or DELETE), the corresponding view is updatable through that statement. For more information about INSTEAD OF triggers

Partitioned Views

If the view is a partitioned view, the view is updatable, subject to certain restrictions. When it is needed, the Database Engine distinguishes local partitioned views as the views in which all participating tables and the view are on the same instance of SQL Server, and distributed partitioned views as the views in which at least one of the tables in the view resides on a different or remote server.

A partitioned view is a view defined by a UNION ALL of member tables structured in the same way, but stored separately as multiple tables in either the same instance of SQL Server or in a group of autonomous instances of SQL Server servers, called federated database servers.

--Partitioned view as defined on Server1

CREATE VIEW Customers

AS

--Select from local member table.

SELECT *

FROM CompanyData.dbo.Customers_33

UNION ALL

--Select from member table on Server2.

SELECT *

FROM Server2.CompanyData.dbo.Customers_66

UNION ALL

--Select from mmeber table on Server3.

SELECT *

FROM Server3.CompanyData.dbo.Customers_99