Thursday 18 July 2013

Interview questions on ssis,sql server and ssrs

1)rendering extensions in ssrs?

2)typical scenario u hav faced?

3)drilldown and drillthrough?

4)asynchronous and synchronous transformations? 

5)examples of synchronous and asynchronous transformations? done

6)join and union difference?

7)joins types used in database development?

8)what type of reports u have created?

9)do you use any tools apart from ssis,ssrs and ssas?

10)type 1 and type 2 dimensions?

11)what is datawarehouse?

12)do you use datawarehouse or database?

13)do you work on rolebased security and level in that?

14)what is primarykey? 

15)what is difference b/w join and union?

16)diff b/w truncate and delete?

17)how to do the logging in ssis?

18)how to optimize the performance of ssis packages?

19)difference b/w lookup and fuzzy lookup?

 20)how to store the eventinfo of ssis pkg into sql server?

21)do u involved in optimizing the sql queries?

22)when iam loading the data from flat file source what
should i  consider?

23)what is the taskhost container?

24)does it in the controlflow?

25)how to setup a connectionstring dynamically?

26)what is the union operator?

27)what is the variable used for connectionstring?

28)what is lookup transformation?

29)what are ddl commands?

30)what is correlated subquery?

31)what is the partitioned view?

32)do you work on subscriptions in ssrs?

33)can we use where with truncate?

34)howmany buffers used in a transformation?

35)did you involve in any document design?

36)what are the limitations of ssrs?

37)what type of reports u have created?

38)who is your client?

39)why should you go for drilldown and drillthrough reports in which situation you used it?

How to store the eventinformation of ssis packages into sql server?

Wednesday 17 July 2013

Partitioned table and views example

 Creating a Partitioned View


Creating a Partitioned
View:
A partitioned view joins horizontally partitioned data from a
set of member tables across one or more servers, making
the data appear as if from one table. Microsoft® SQL
Server™ 2000 distinguishes between local and distributed
partitioned views. In a local partitioned view, all
participating tables and the view reside on the same
instance of SQL Server. In a distributed partitioned view, at
least one of the participating tables resides on a different
(remote) server. In addition, SQL Server 2000 differentiates
between partitioned views that are updatable and views
that are read-only copies of the underlying tables.
Distributed partitioned views can be used to implement a
federation of database servers. A federation is a group of
servers administered independently, but which cooperate
to share the processing load of a system. Forming a
federation of database servers by partitioning data is the
mechanism that enables you to scale out a set of servers to
support the processing requirements of large, multitiered
Web sites. For more information, see Designing Federated
Database Servers.
Before implementing a partitioned view, you must first
partition a table horizontally. In designing a partitioning
scheme, it must be clear what data belongs to each
member table. The original table is replaced with several
smaller member tables. Each member table has the same
number of columns as the original table, and each column
has the same attributes (such as data type, size, collation)
as the corresponding column in the original table. If you
are creating a distributed partitioned view, each member
table is on a separate member server. For the greatest
location transparency, the name of the member databases
should be the same on each member server, although this
is not a requirement. For example: Server1.CustomerDB,
Server2.CustomerDB, Server3.CustomerDB.
You design the member tables so that each table stores a
horizontal slice of the original table based on a range of
key values. The ranges are based on the data values in a
partitioning column. The range of values in each member
table is enforced by a CHECK constraint on the partitioning
column, and ranges cannot overlap. For example, you
cannot have one table with a range from 1 through 200000,
and another with a range from 150000 through 300000
because it would not be clear which table contains the
values from 150000 through 200000.
SQL Server 2000 22 out of 26 rated this helpful
7/15/13 Creating a Partitioned View
msdn.microsoft.com/en-us/library/aa933141(v=sql.80).aspx 2/7
values from 150000 through 200000.
For example, you are partitioning a Customer table into
three tables. The CHECK constraint for these tables is:
-- On Server1:
CREATE TABLE Customers_33
(CustomerID INTEGER PRIMARY KEY
CHECK (CustomerID BETWEEN 1
AND 32999),
... -- Additional column definitions)
-- On Server2:
CREATE TABLE Customers_66
(CustomerID INTEGER PRIMARY KEY
CHECK (CustomerID BETWEEN 3
3000 AND 65999),
... -- Additional column definitions)
-- On Server3:
CREATE TABLE Customers_99
(CustomerID INTEGER PRIMARY KEY
CHECK (CustomerID BETWEEN 6
6000 AND 99999),
... -- Additional column definitions)
After creating the member tables, you define a distributed
partitioned view on each member server, with each view
having the same name. This allows queries referencing the
distributed partitioned view name to run on any of the
member servers. The system operates as if a copy of the
original table is on each member server, but each server
has only a member table and a distributed partitioned
view. The location of the data is transparent to the
application.
You build the distributed partitioned views by:
Adding linked server definitions on each member
server containing the connection information needed
to execute distributed queries on the other member
servers. This gives a distributed partitioned view
access to data on the other servers.
Setting the lazy schema validation option, using
sp_serveroption, for each linked server definition
used in distributed partitioned views. This optimizes
performance by ensuring the query processor does
not request meta data for any of the linked tables
until data is actually needed from the remote
member table.
Creating a distributed partitioned view on each
member server. The views use distributed SELECT
statements to access data from the linked member
servers, and merges the distributed rows with rows
from the local member table.
7/15/13 Creating a Partitioned View
msdn.microsoft.com/en-us/library/aa933141(v=sql.80).aspx 3/7
from the local member table.
To create distributed partitioned views for the preceding
example, you must:
Add a linked-server definition named Server2 with
the connection information for Server2, and a linked
server definition named Server3 for access to
Server3.
Create this distributed partitioned view:
CREATE VIEW Customers AS
SELECT * FROM CompanyDatabase.Table
Owner.Customers_33
UNION ALL
SELECT * FROM Server2.CompanyDataba
se.TableOwner.Customers_66
UNION ALL
SELECT * FROM Server3.CompanyDataba
se.TableOwner.Customers_99
Perform the same steps on Server2 and Server3.
Updatable Partitioned Views
If a local or distributed partitioned view is not updatable, it
can serve only as a read-only copy of the original table. An
updatable partitioned view can exhibit all the capabilities of
the original table.
A view is considered an updatable partitioned view if:
The view is a set of SELECT statements whose
individual result sets are combined into one using
the UNION ALL statement. Each individual SELECT
statement references one SQL Server base table.
The table can be either a local table or a linked table
referenced using a four-part name, the
OPENROWSET function, or the OPENDATASOURCE
function (you cannot use an OPENDATASOURCE or
OPENROWSET function that specifies a pass-through
query).
The view will not be updatable if a trigger or cascading
update or delete is defined on one or more member
tables.
Table Rules
Member tables are defined in the FROM clause in each
SELECT statement in the view definition. Each member table
must adhere to these rules:
Member tables cannot be referenced more than
once in the view.
Member tables cannot have indexes created on any
computed columns.
7/15/13 Creating a Partitioned View
msdn.microsoft.com/en-us/library/aa933141(v=sql.80).aspx 4/7
computed columns.
Member tables must have all PRIMARY KEY
constraints on an identical number of columns.
Member tables must have the same ANSI padding
setting. For more information about the ANSI
padding setting, see SET ANSI_PADDING.
Column Rules
Columns are defined in the select list of each SELECT
statement in the view definition. The columns must follow
these rules.
All columns in each member table must be included
in the select list. SELECT * FROM <member table> is
acceptable syntax.
Columns cannot be referenced more than once in
the select list.
The columns must be in the same ordinal position in
the select list
The columns in the select list of each SELECT
statement must be of the same type (including data
type, precision, scale, and collation). For example,
this view definition fails because the first column in
both SELECT statements does not have the same
data type:
CREATE VIEW NonUpdatable
AS
SELECT IntPrimaryKey, IntPartNmbr
FROM FirstTable
UNION ALL
SELECT NumericPrimaryKey, IntPartNmbr
FROM SecondTable
Partitioning Column Rules
A partitioning column exists on each member table and,
through CHECK constraints, identifies the data available in
that specific table. Partitioning columns must adhere to
these rules:
Each base table has a partitioning column whose key
values are enforced by CHECK constraints. The key
ranges of the CHECK constraints in each table do
not overlap with the ranges of any other table. Any
given value of the partitioning column must map to
only one table. The CHECK constraints can only use
these operators: BETWEEN, AND, OR, <, <=, >, >=,
=.
The partitioning column cannot be an identity,
default or timestamp column.
The partitioning column must be in the same ordinal
7/15/13 Creating a Partitioned View
msdn.microsoft.com/en-us/library/aa933141(v=sql.80).aspx 5/7
The partitioning column must be in the same ordinal
location in the select list of each SELECT statement in
the view. For example, the partitioning column is
always the first column in each select list, or the
second column in each select list, and so on.
Partitioning columns cannot allow nulls.
Partitioning columns must be a part of the primary
key of the table.
Partitioning columns cannot be computed columns.
There must be only one constraint on the
partitioning column. If there is more than one
constraint, SQL Server ignores all the constraints and
will not consider them when determining whether or
not the view is a partitioned view.
There are no restrictions on the updatability of the
partitioning columns.
A partitioned column that meets all these rules will support
all of the optimizations that are supported by the SQL
Server 2000 query optimizer. For more information, see
Resolving Distributed Partitioned Views.
Data Modification Rules
In addition to the rules defined for updatable partitioned
views, data modification statements referencing the view
must adhere to the rules defined for INSERT, UPDATE and
DELETE statements.
Note You can modify data through a partitioned view only
if you install Microsoft SQL Server 2000 Enterprise Edition
or Microsoft. SQL Server 2000 Developer Edition.
INSERT Statements
INSERT statements add data to the member tables through
the partitioned view. The INSERT statements must adhere
to these rules:
All columns must be included in the INSERT
statement even if the column can be NULL in the
base table or has a DEFAULT constraint defined in
the base table.
The DEFAULT keyword cannot be specified in the
VALUES clause of the INSERT statement.
INSERT statements must supply a value that satisfies
the logic of the CHECK constraint defined on the
partitioning column for one of the member tables.
INSERT statements are not allowed if a member
table contains a column with an identity property.
7/15/13 Creating a Partitioned View
msdn.microsoft.com/en-us/library/aa933141(v=sql.80).aspx 6/7
INSERT statements are not allowed if a member
table contains a timestamp column.
INSERT statements are not allowed if there is a selfjoin
with the same view or any of the member table.
UPDATE Statements
UPDATE statements modify data in one or more of the
member tables through the partitioned view. The UPDATE
statements must adhere to these rules:
UPDATE statements cannot specify the DEFAULT
keyword as a value in the SET clause even if the
column has a DEFAULT value defined in the
corresponding member table
The value of a column with an identity property
cannot be changed: however, the other columns can
be updated.
The value of a PRIMARY KEY cannot be changed if
the column contains text, image or ntext data.
Updates are not allowed if a base table contains a
timestamp column.
Updates are not allowed if there is a self-join with
the same view or any of the member tables.
The DEFAULT keyword cannot be specified in the
SET clause of the UPDATE statement.
DELETE Statements
DELETE statements remove data in one or more of the
member tables through the partitioned view. The DELETE
statements must adhere to this rule:
DELETE statements are not allowed if there is a selfjoin
with the same view or any of the member tables.
Distributed Partition View Rules
In addition to the rules defined for partitioned views,
distributed (remote) partition views have these additional
conditions:
A distributed transaction will be started to ensure
atomicity across all nodes affected by the update.
The XACT_ABORT SET option must be set to ON.
smallmoney and smalldatetime columns in remote
tables are mapped as money and datetime
respectively. Consequently, the corresponding
columns in the local tables should also be money
and datetime.
7/15/13 Creating a Partitioned View
msdn.microsoft.com/en-us/library/aa933141(v=sql.80).aspx 7/7
Any linked server cannot be a loopback linked
server, that is, a linked server that points to the
same instance of SQL Server.
A view that references partitioned tables without following
all these rules may still be updatable if there is an INSTEAD
OF trigger on the view. The query optimizer, however, may
not always be able to build execution plans for a view with
an INSTEAD OF trigger that are as efficient as the plans for

a partitioned view that follows all of the rules.


--partition table1

create table partitiontable1(
                            id int,Name varchar(50),
                            check(id between 20 and 30)
                            )
                            
insert into partitiontable1
 values(21,'a'),(22,'b'),(23,'c'),(24,'b'),(25,'d'),(26,'e'),(27,'y'),(28,'e'),(29,'w'),(30,'r'),(11,'m')
 --partition table 2
 create table partitiontable2(
                            id int,Name varchar(50),
                            check(id between 20 and 30)
                            )
                            
insert into partitiontable2


 values(21,'a'),(22,'b'),(23,'c'),(24,'b'),(25,'d'),(26,'e'),(27,'y'),(28,'e'),(29,'w'),(30,'r'),(11,'m')

 --partition table 3
 create table partitiontable3(
                            id int,Name varchar(50),
                            check(id between 20 and 30)
                            )
                            
insert into partitiontable3
 values(21,'a'),(22,'b'),(23,'c'),(24,'b'),(25,'d'),(26,'e'),(27,'y'),(28,'e'),(29,'w'),(30,'r'),(11,'m')



 select * from partitiontable3

 --now we can club the data using union all 

 select * from partitiontable
  union all
  select * from partitiontable2
  union all
  select * from partitiontable3 























                            

Wednesday 5 June 2013

IMPORTANT QUERIES?


--1)Duplicate records

with cte as
(

select *,ROW_NUMBER() over(partition by id order by id) as
 duplicateids from duptable
)
delete from cte where duplicateids>1

select * from employee

--2)highest salary
with cte as
(
select salary,ROW_NUMBER() over ( order by salary desc) as Highsalaries
 from employee

)
select salary from cte  where  Highsalaries=3

--3)highest salary without using subquery,cte,functions?

select * from employee a where 1=(select COUNT(distinct salary) from employee B where a.salary>B.salary)



select ISNULL(t1.id,t2.id) from tab1 t1
right join
tab2 t2
on
t1.id=t2.id
where t2.id =null


--4)inner join result
SELECT isnull(t1.id,t2.ID)
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.ID = t2.ID


--5)left join result

select isnull(t1.id,t2.id )
from
tab1 t1 left join  tab2 t2
on t1.id=t2.id
where t2.id is null

--6)self join example

select * from Employeeselfjoin

select e2.name as   emp ,e1.name as mgr
from
Employeeselfjoin e1
inner join
Employeeselfjoin e2
on
e1.EmployeeID=e2.ManagerID

--7)how to seperate the domain name from a given name

select SUBSTRING('yjreddy@yahoo.com',
                   charindex('@','yjreddy@yahoo.com')+1,LEN('yjreddy@yahoo.com'))

select CHARINDEX('@','yjreddy@yahoo.com')+1





create table Nametablesubstring(Name varchar(max))

insert into Nametablesubstring values('yjredy'),('vsrikar'),('Mershad'),('yanil')


--8)Substring Example
select SUBSTRING([name],1,1) as intital from Nametablesubstring

--9)Replace and stuff

select REPLACE('yjreddy ?','?','cricketer and activist')


select STUFF('janardhanareddy',2,10,'india')


--10)update a table using case

update table set salary=(
case
 when salary=20000 then salary+5000
 when salary=30000 the salary+2000
 else
 salary+5000
 end



Saturday 25 May 2013

Update using case statement


create table EmployeeTest(id int,Name varchar(50),Address varchar(50),Salary float)

insert into EmployeeTest values(101,'yjreddy','hyderabad',42000)

insert into EmployeeTest values(102,'Dmreddy','Vizag',32000)


update EmployeeTest set Salary=
case
when Salary=42000 then Salary+10000
end

Monday 11 March 2013

Stored Procedures in sql server and Examples



Stored procedures—Introduction
SQL Server Stored Procedure   
 
(Introduction)
http://www.mssqltips.com/images/previous.gif http://www.mssqltips.com/images/next.gif
Overview
A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again.  So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure.
In addition to running the same SQL code over and over again you also have the ability to pass parameters to the stored procedure, so depending on what the need is the stored procedure can act accordingly based on the parameter values that were passed.
Take a look through each of these topics to learn how to get started with stored procedure development for SQL Server.
You can either use the outline on the left or click on the arrows to the right or below to scroll through each of these topics.
Creating a simple stored procedure   
 
(CREATE PROCEDURE)
http://www.mssqltips.com/images/previous.gif http://www.mssqltips.com/images/next.gif
Overview
As mentioned in the tutorial overview a stored procedure is nothing more than stored SQL code that you would like to use over and over again.  In this example we will look at creating a simple stored procedure.
Explanation
Before you create a stored procedure you need to know what your end result is, whether you are selecting data, inserting data, etc.. 
In this simple example we will just select all data from the Person.Address table that is stored in the AdventureWorks database.
So the simple T-SQL code would be as follows which will return all rows from this table.
SELECT * FROM AdventureWorks.Person.Address
To create a stored procedure to do this the code would look like this:
CREATE PROCEDURE uspGetAddress
AS
SELECT * FROM AdventureWorks.Person.Address
GO
To call the procedure to return the contents from the table specified, the code would be:
EXEC uspGetAddress
--or just simply
uspGetAddress

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.
On 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.
Also, you can not change database context within the stored procedure such as using "USE dbName" the reason for this is because this would be a separate batch and a stored procedure is a collection of only one batch of statements.

How to create a SQL Server stored procedure with parameters  
http://www.mssqltips.com/images/previous.gifhttp://www.mssqltips.com/images/next.gif
Overview
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 topic we will look at passing parameter values to a stored procedure.
Explanation
Just like you have the ability to use parameters with your SQL code you can also setup your stored procedures to except one or more parameter values.
One Parameter
In this example we will query the Person.Address table from the AdventureWorks 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 uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
GO
To call this stored procedure we would execute it as follows:
EXEC uspGetAddress @City = 'New York'
We can also do the same thing, but allow the users to give us a starting point to search the data.  Here we can change the "=" to a LIKE and use the "%" wildcard.
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City LIKE @City + '%'
GO
In both of the proceeding examples it assumes that a parameter value will always be passed. If you try to execute the procedure without passing a parameter value you will get an error message such as the following:
Msg 201, Level 16, State 4, Procedure uspGetAddress, Line 0
Procedure or function 'uspGetAddress' expects parameter '@City', which was not supplied.
Default Parameter Values
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 uspGetAddress @City nvarchar(30) = NULL
AS
SELECT *
FROM AdventureWorks.Person.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 uspGetAddress @City nvarchar(30) = NULL
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = ISNULL(@City,City)
GO
Multiple Parameters
Setting up multiple parameters is very easy to do.  You just need to list each parameter and the data type separated by a comma as shown below.
CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = ISNULL(@City,City)
AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%'
GO
To execute this you could do any of the following:
EXEC uspGetAddress @City = 'Calgary'
--or
EXEC uspGetAddress @City = 'Calgary', @AddressLine1 = 'A'
--or
EXEC uspGetAddress @AddressLine1 = 'Acardia'
-- etc...

Returning stored procedure parameter values to a calling stored procedure   
 
(OUTPUT)
http://www.mssqltips.com/images/previous.gifhttp://www.mssqltips.com/images/next.gif
Overview
In a previous topic we discussed how to pass parameters into a stored procedure, but another option is to pass parameter values back out from a stored procedure.  One option for this may be that you call another stored procedure that does not return any data, but returns parameter values to be used by the calling stored procedure.
Explanation
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".
Simple Output
CREATE PROCEDURE uspGetAddressCount @City nvarchar(30), @AddressCount int OUTPUT
AS
SELECT @AddressCount = count(*)
FROM AdventureWorks.Person.Address
WHERE City = @City
Or it can be done this way:
CREATE PROCEDURE uspGetAddressCount @City nvarchar(30), @AddressCount int OUT
AS
SELECT @AddressCount = count(*)
FROM AdventureWorks.Person.Address
WHERE City = @City
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 uspGetAddressCount @City = 'Calgary', @AddressCount = @AddressCount OUTPUT
SELECT @AddressCount
This can also be done as follows, where the stored procedure parameter names are not passed.
DECLARE @AddressCount int
EXEC uspGetAddressCount 'Calgary', @AddressCount OUTPUT
SELECT @AddressCount

Using try catch in SQL Server stored procedures   
 
(TRY...CATCH)
http://www.mssqltips.com/images/previous.gif http://www.mssqltips.com/images/next.gif
Overview
A great new option that was added in SQL Server 2005 was the ability to use the Try..Catch paradigm that exists in other development languages.  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.
Explanation
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

Using comments in a SQL Server stored procedure   
http://www.mssqltips.com/images/previous.gif http://www.mssqltips.com/images/next.gif
Overview
One very helpful thing to do with your stored procedures is to add comments to your code.  This helps you to know what was done and why for future reference, but also helps other DBAs or developers that may need to make modifications to the code.
Explanation
SQL Server offers two types of comments in a stored procedure; line comments and block comments.   The following examples show you how to add comments using both techniques.  Comments are displayed in green in a SQL Server query window.
Line Comments
To create line comments you just use two dashes "--" in front of the code you want to comment.  You can comment out one or multiple lines with this technique.
In this example the entire line is commented out.
-- this procedure gets a list of addresses based
-- on the city value that is passed
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
GO
This next example shows you how to put the comment on the same line.
-- this procedure gets a list of addresses based on the city value that is passed
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City -- the @City parameter value will narrow the search criteria
GO
Block Comments
To create block comments the block is started with "/*" and ends with "*/".   Anything within that block will be a comment section.
/*
-this procedure gets a list of addresses based
 on the city value that is passed
-this procedure is used by the HR system     
*/
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
GO
Combining Line and Block Comments
You can also use both types of comments within a stored procedure.
/*
-this procedure gets a list of addresses based
 on the city value that is passed
-this procedure is used by the HR system     
*/
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City -- the @City parameter value will narrow the search criteria
GO

Naming conventions for SQL Server stored procedures   
http://www.mssqltips.com/images/previous.gif http://www.mssqltips.com/images/next.gif
Overview
One good thing to do for all of your SQL Server objects is to come up with a naming convention to use.  There are not any hard and fast rules, so this is really just a guideline on what should be done.
Explanation
SQL Server uses object names and schema names to find a particular object that it needs to work with.  This could be a table, stored procedure, function ,etc...
It is a good practice to come up with a standard naming convention for you objects including stored procedures.

Do not use sp_ as a prefix
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.

Standardize on a Prefix
It is a good idea to come up with a standard prefix to use for your stored procedures.  As mentioned above do not use "sp_", so here are some other options.
  • usp_
  • sp
  • usp
  • etc...
To be honest it does not really matter what you use.  SQL Server will figure out that it is a stored procedure, but it is helpful to differentiate the objects, so it is easier to manage.
So a few examples could be:
  • spInsertPerson
  • uspInsertPerson
  • usp_InsertPerson
  • InsertPerson
Again this is totally up to you, but some standard is better than none.

Naming Stored Procedure Action
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:
  • uspInsertPerson
  • uspGetPerson
  • spValidatePerson
  • SelectPerson
  • etc...
Another option is to put the object name first and the action second, this way all of the stored procedures for an object will be together.
  • uspPersonInsert
  • uspPersonDelete
  • uspPersonGet
  • etc...
Again, this does not really matter what action words that you use, but this will be helpful to classify the behavior characteristics.

Naming Stored Procedure Object
The last part of this is the object that you are working with.  Some of these may be real objects like tables, but others may be business processes.  Keep the names simple, but meaningful.  As your database grows and you add more and more objects you will be glad that you created some standards.
So some of these may be:
  • uspInsertPerson - insert a new person record
  • uspGetAccountBalance - get the balance of an account
  • uspGetOrderHistory - return list of orders

Schema Names
Another thing to consider is the schema that you will use when saving the objects.  A schema is the a collection of objects, so basically just a container.  This is useful if you want to keep all utility like objects together or have some objects that are HR related, etc...
This logical grouping will help you differentiate the objects further and allow you to focus on a group of objects.
Here are some examples of using a schema:
  • HR.uspGetPerson
  • HR.uspInsertPerson
  • UTIL.uspGet
  • UTIL.uspGetLastBackupDate
  • etc...
To create a new schema you use the CREATE SCHEMA command
Here is a simple example to create a new schema called "HR" and giving authorization to this schema to "DBO".
CREATE SCHEMA [HumanResources] AUTHORIZATION [dbo]

Putting It All Together
So you basically have four parts that you should consider when you come up with a naming convention:
  • Schema
  • Prefix
  • Action
  • Object
Take the time to think through what makes the most sense and try to stick to your conventions.

Reducing amount of network data for SQL Server stored procedures  
 
(SET NOCOUNT ON)
http://www.mssqltips.com/images/previous.gifhttp://www.mssqltips.com/images/next.gif
Overview
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.
Explanation
As mentioned above there is not really any reason to return messages about what is occuring within SQL Server when you run a stored procedure.  If you are running things from a query window, this may be useful, but most end users that run stored procedures through an application would never see these messages. 
You can still use @@ROWCOUNT to get the number of rows impacted by a SQL statement, so turning SET NOCOUNT ON will not change that behavior.
Not using SET NOCOUNT ON
Here is an example without using SET NOCOUNT ON:
-- 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:
(23 row(s) affected)
Using SET NOCOUNT ON
This example uses the SET NOCOUNT ON as shown below.  It is a good practice to put this at the beginning of the stored procedure.
-- 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
This example uses SET NOCOUNT ON, but will still return the number of rows impacted by the previous statement.  This just shows that this still works.
-- 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:
23
SET NOCOUNT OFF
If you wanted to turn this behavior off, you would just use the command "SET NOCOUNT OFF".


Deleting a SQL Server stored procedure   
 
(DROP PROCEDURE)
http://www.mssqltips.com/images/previous.gif http://www.mssqltips.com/images/next.gif
Overview
In addition to creating stored procedures there is also the need to delete stored procedures.  This topic shows you how you can delete stored procedures that are no longer needed.
Explanation
The syntax is very straightforward to drop a stored procedure, here are some examples.
Dropping Single Stored Procedure
To drop a single stored procedure you use the DROP PROCEDURE or DROP PROC command as follows.
DROP PROCEDURE uspGetAddress
GO
-- or
DROP PROC uspGetAddress
GO
-- or
DROP PROC dbo.uspGetAddress -- also specify the schema
Dropping Multiple Stored Procedures
To drop multiple stored procedures with one command you specify each procedure separated by a comma as shown below.
DROP PROCEDURE uspGetAddress, uspInsertAddress, uspDeleteAddress
GO
-- or
DROP PROC uspGetAddress, uspInsertAddress, uspDeleteAddress
GO


Modifying an existing SQL Server stored procedure   
 
(ALTER PROCEDURE)
http://www.mssqltips.com/images/previous.gif http://www.mssqltips.com/images/next.gif
Overview
When you first create your stored procedures it may work as planned, but how to do you modify an existing stored procedure.  In this topic we look at the ALTER PROCEDURE command and it is used.
Explanation
Modifying or ALTERing a stored procedure is pretty simple.  Once a stored procedure has been created it is stored within one of the system tables in the database that is was created in.  When you modify a stored procedure the entry that was originally made in the system table is replaced by this new code.  Also, SQL Server will recompile the stored procedure the next time it is run, so your users are using the new logic.  The command to modify an existing stored procedure is ALTER PROCEDURE or ALTER PROC.
Modifying an Existing Stored Procedure
Let's say we have the following existing stored procedure:  This allows us to do an exact match on the City.
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
GO
Let's say we want to change this to do a LIKE instead of an equals.
To change the stored procedure and save the updated code you would use the ALTER PROCEDURE command as follows.
ALTER PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City LIKE @City + '%'
GO
Now the next time that the stored procedure is called by an end user it will use this new logic.
SQL Server Stored Procedure   
 
(Introduction)
http://www.mssqltips.com/images/previous.gif http://www.mssqltips.com/images/next.gif
Overview
A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again.  So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure.
In addition to running the same SQL code over and over again you also have the ability to pass parameters to the stored procedure, so depending on what the need is the stored procedure can act accordingly based on the parameter values that were passed.
Take a look through each of these topics to learn how to get started with stored procedure development for SQL Server.
You can either use the outline on the left or click on the arrows to the right or below to scroll through each of these topics.


/*SP to get all data from a table

create procedure usp_Getalldata
as
begin

select * from employee
end

exec usp_Getalldata

/*Procedure by single parameter*/

create procedure usp_getbyparameter_id_name @id int,@name varchar(50)
as
begin
select * from employee
where @id=id
end

exec usp_getbyparameter_id_name 1,'Mary'

/*optional parameter*/
CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL
AS
SELECT *
FROM employee
WHERE City = @City

/*Multiple parameters*/

create procedure Multiple_Parameters @id int,@name varchar(50)
as
begin
select * from employee
where id=@id or name=@name
end

Exec Multiple_parameters 1,james