SQL Server Stored Procedure with Parameters


By:
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 accept one or more parameter values.  All examples use the AdventureWorks database.

Creating a SQL Stored Procedure with Parameters

  1. To create a stored procedure with parameters using the following syntax:
  2. CREATE PROCEDURE dbo.uspGetAddress @City nvarchar(30) AS
  3. See details and examples below

SQL Server Query to Turn into a Stored Procedure

Below is the query we want to use to create the stored procedure.

USE AdventureWorks
GO

SELECT * 
FROM Person.Address
GO

The idea is to create the stored procedure where the City is passed into the stored procedure so it can create dynamic results. This can be done as follows using a variable.  If we run the below code it will return just the results for New York.

USE AdventureWorks
GO

DECLARE @City nvarchar(30)
SET @City = 'New York'

SELECT * 
FROM Person.Address
WHERE City = @City
GO

We could use this approach and keep updating the @City variable, but there is a better way to do this by creating a stored procedure.

Create SQL Server Stored Procedure with 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.

USE AdventureWorks
GO

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

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

EXEC dbo.uspGetAddress @City = 'New York'

Deleting the Stored Procedure

If you created the stored procedure and you want to recreate the stored procedure with the same name, you can delete it using the following before trying to create it again.

USE AdventureWorks
GO

DROP PROCEDURE dbo.uspGetAddress
GO

If you try to create the stored procedure and it already exists you will get an error message.

Msg 2714, Level 16, State 3, Procedure uspGetAddress, Line 1 [Batch Start Line 33]
There is already an object named 'uspGetAddress' in the database.

SQL Server Stored Procedure with Parameter using Wildcard

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.

USE AdventureWorks
GO

CREATE PROCEDURE dbo.uspGetAddress @City nvarchar(30) 
AS 
SELECT * 
FROM Person.Address 
WHERE City LIKE @City + '%' 
GO

This can be run as follows to find all Cities that start with New.

EXEC dbo.uspGetAddress @City = 'New'

SQL Server Stored Procedure Error When Parameter Not Passed

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:

EXEC dbo.uspGetAddress
Msg 201, Level 16, State 4, Procedure uspGetAddress, Line 0
Procedure or function 'uspGetAddress' expects parameter '@City', which was not supplied.

SQL Server Stored Procedure using NULL as Default Parameter

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.

USE AdventureWorks
GO

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

If we run the following it will work, but no data will be returned.

EXEC dbo.uspGetAddress

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. (Note: if the City column has NULL values this will not include these values. You will have to add additional logic for City IS NULL)

USE AdventureWorks
GO

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

Now if we run the below command, all data will be returned from the table.

EXEC dbo.uspGetAddress

Create SQL Server Stored Procedure with 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.

USE AdventureWorks
GO

CREATE PROCEDURE dbo.uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL
AS
SELECT *
FROM Person.Address
WHERE City = ISNULL(@City,City)
AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%'
GO

To execute this you could do any of the following:

-- return rows where City equals Calgary
EXEC dbo.uspGetAddress @City = 'Calgary' 

-- return rows where City equals Calgary and AddresLine1 contains A
EXEC dbo.uspGetAddress @City = 'Calgary', @AddressLine1 = 'A' 

-- return rows where AddresLine1 contains Acardia
EXEC dbo.uspGetAddress @AddressLine1 = 'Acardia'

-- this will return all rows
EXEC dbo.uspGetAddress 

Create or Alter SQL Server Stored Procedure

In SQL Server 2016 and later there is the ability to either CREATE a new stored procedure if it does not already exist or ALTER the procedure if it does exist.  Below is a sample of the syntax to make an update to the stored procedure where we only want to return a few columns instead of all columns.

USE AdventureWorks
GO

CREATE OR ALTER PROCEDURE dbo.uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL
AS
SELECT AddressLine1, AddressLine2, City, PostalCode
FROM Person.Address
WHERE City = ISNULL(@City,City)
AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%'
GO





Comments For This Article




Wednesday, February 7, 2024 - 10:48:50 AM - Kevin Bourne Wood Back To Top (91930)
SWEET! I created a stored procedure to query my military history DB. saves me the trouble of generating the query each time to find a specific conflict.

Friday, December 22, 2023 - 2:39:33 AM - Hamza Back To Top (91812)
this is what I am looking for WHERE City = ISNULL(@City,City).
Thanks man its working perfectly

Monday, September 26, 2022 - 6:48:51 AM - Sumit Back To Top (90522)
Very Helpful for me , as I'm exploring just want to know that is there any difference between stored procedure and function in SQL server as they both work same.

Monday, February 14, 2022 - 7:58:56 AM - Jamal Mustafa Back To Top (89785)
Yes, very helpful, indeed, thank you!

Wednesday, December 15, 2021 - 12:53:06 PM - Omer Salim Mohmand Back To Top (89586)
I really enjoyed going through this nice tutorial. I really appreciate your great work.
Thanks!

Friday, October 8, 2021 - 6:27:26 AM - SimpleSQLTutorials Back To Top (89320)
Also remember two interesting facts about stored procedure parameters:

1. When you execute the stored procedure, you don't NEED to outline the names of the parameters. For example, this would have been OK:

EXEC dbo.uspGetAddress 'New York'

Trouble is when you do that, you need to outline the parameters in the correct order they are defined in the SP

2. As long as you outline parameter names when you execute your SP, the order of your parameters can be in any way you want. The parameter names and values don't need to be in the same order they are defined in the SP!

Tuesday, February 16, 2021 - 9:52:22 AM - Greg Robidoux Back To Top (88245)
Hi Ren,

you could try something like this

SELECT *
FROM table
WHERE ( col is null or col in (1,2,3) )


Tuesday, February 16, 2021 - 2:44:35 AM - ren Back To Top (88244)
is there a way to have null default parameter to be used IN clause

Wednesday, April 4, 2018 - 7:40:28 AM - maanasa sai Back To Top (75603)

 

 hi thanks for all the examples. It was very helpful.

It would be great if the execution is also showed.

thank you :)


Wednesday, January 10, 2018 - 11:07:13 AM - Greg Robidoux Back To Top (74937)

Hi Will,

there is not any real purpose to have a prefix for any of the objects.  People just do this so then can identify what the object is based on the name, but other than that there is no real purpose.


Wednesday, January 10, 2018 - 10:49:36 AM - Will Back To Top (74936)

 

 Did I miss the part where you explain the prupose of the prefix of usp in the Proc name? What does that mean or stand for?


Wednesday, July 5, 2017 - 2:46:17 AM - Mister C. Donald Back To Top (58898)

 Very Helpful AMK

 


Tuesday, April 4, 2017 - 10:03:10 AM - omprakash Back To Top (54223)

 

 

nice tutorial but you should add more pictuers .it will very helpfull for all ,

thankyou..


Tuesday, February 28, 2017 - 2:32:17 AM - redlina Back To Top (46753)

 very usefull 

 


Monday, February 20, 2017 - 8:03:45 AM - Gunel Back To Top (46521)

Very useful.Thanks!


Tuesday, December 13, 2016 - 8:00:11 AM - James Back To Top (44954)

Awesome, Thanks.


Friday, September 30, 2016 - 6:50:21 AM - jyothi Back To Top (43464)

 i created stored procedure like this 

USE [Reporting_Tool]

GO

/****** Object:  StoredProcedure [dbo].[dlt]    Script Date: 2016-09-30 3:34:45 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

ALTER PROCEDURE [dbo].[dlt]

AS

SELECT * FROM dbo.Table1

DELETE FROM Table1 WHERE  DATEDIFF(DD,DateTime,GETDATE())>=10

--select * from Table1

--EXEC dlt

 

 In server agent created job named as dlt -----> in that job under step - a) general 

                                                                                                        database name :Reporting_Tool

                                                                                   command:EXEC dlt

                                                                     b)advanced

                                                                                       output file:C:\zzz\abc.txt

                                                                                  and clicked on append output to existing file

in shedule --> Name :job1

type:Recurring and clicked on enable

frequency occurs:Daily

occurs every :5min

No end date and finally cliked ok

but it is not executing and taking backup for evry 5min

can u tell me is this procedure is right or wrong ?????

THANKS IN ADVANCE.......

 

 


Thursday, September 29, 2016 - 9:45:40 AM - Greg Robidoux Back To Top (43452)

Hi Jyothi,

you could use SQL Agent to schedule a stored procedure to run as needed.

Check out some of these tips for using SQL Agent: https://www.mssqltips.com/sql-server-tip-category/27/sql-server-agent/

-Greg


Thursday, September 29, 2016 - 7:49:25 AM - jyothi Back To Top (43447)

 

 

this stored procedure doesn't not run automatically ???

i want to write code for "to delete 3months old data & run automatically after every 3months using datetime as column name??

it is possible to do like this?? help me!!!!!!


Monday, September 12, 2016 - 2:48:11 PM - Gary Stephens Back To Top (43307)

All the examples above were useful for my stored proc development. Thanks!


Monday, July 25, 2016 - 5:19:54 AM - Vinay Back To Top (42967)

Very useful.


Monday, June 20, 2016 - 4:08:48 AM - NAidui Back To Top (41726)

 Good Lession

 


Wednesday, May 18, 2016 - 1:09:13 PM - Loki Back To Top (41511)

Nice .simple.clear


Friday, May 13, 2016 - 9:30:13 AM - Gerald Back To Top (41482)

 

 big help


Monday, January 25, 2016 - 9:51:30 AM - raju Back To Top (40492)

 REQUIREMENT: Produce a report showing the number of days between successive visits. Leave the column blank for the first visit for each patient.    The results should be as follows:

 

PatientNo              VisitNo           VisitDate         DaysSincePrevious

 

1                            1                      12-Jan-2005

 

1                            2                      23-Jan-2005                11

 

1                            3                      28-Jan-2005                5

 

2                            1                      01-Feb-2005

 

2                            2                      08-Feb-2005                7

 

4                            1                      03-Feb-2005

     4                             2                      08-Feb-2005             5                     

create table patients

(

patient_id int,

patient_no int,

initials varchar(30)

)

insert into patients values (1,1,'ABC'),

                                      (2,3,'DEF'),

      (3,4,'HIJ')

SELECT* FROM PATIENTS

create table visits

(

visit_id int,

patient_id int,

visit_no int,

visit_date date

)

insert into visits values (1,1,1,'12-jan-2005'),

                                  (2,1,2,'23-jan-2005'),

 (3,1,3,'28-jan-2005'),

         (4,2,1,'01-feb-2005'),

 (5,2,2,'08-feb-2005'),

 (6,3,1,'03-feb-2005'),

 (7,3,2,'08-feb-2005')

 

SELECT * FROM VISITS

 

 















get free sql tips
agree to terms