Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

what is this sproc doing? 2

Status
Not open for further replies.

rds80

Programmer
Nov 2, 2006
124
US
This is from a SQL Server book:

Code:
Use Northwind
GO
IF OBJECT_ID('dbo.ListCustomersByCity') IS NOT NULL
  DROP PROC dbo.ListCustomersByCity
GO
CREATE PROCEDURE dbo.ListCustomersByCity @Country nvarchar(30)='%'
AS
SELECT City, COUNT(*) AS NumberOfCustomers
FROM Customers
WHERE Country LIKE @Country
GROUP BY City
GO
EXEC dbo.ListCustomersByCity

How is @Country working? Is the where clause reading WHERE Country LIKE @%? Thanks.
 
>> Is the where clause reading WHERE Country LIKE @%?

it is reading it as '%' meaning if nothing is passed in it will grab all countries

--all countries
EXEC dbo.ListCustomersByCity


--Mexico
EXEC dbo.ListCustomersByCity 'mexico'





Denis The SQL Menace
SQL blog:
 
It first creates the variable @country as a nvarchar(30), then it sets a default value of '%'.

So, if the user does not enter a parameter it will look for everything.

So.

EXEC dbo.ListCustomersByCity 'USA'

would run:

SELECT City, COUNT(*) AS NumberOfCustomers
FROM Customers
WHERE Country LIKE 'USA'
GROUP BY City


But:

EXEC dbo.ListCustomersByCity

would run

SELECT City, COUNT(*) AS NumberOfCustomers
FROM Customers
WHERE Country LIKE '%'
GROUP BY City

Running the script will create the procedure, and then test the default action.

-SQLBill


Posting advice: FAQ481-4875
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top