Saturday, May 10, 2008

Stored procedure with a parameter and output parameter

The following example is for Microsoft SqlServer. One can try and run this is for learners.
Step-1 Create a Stored Procedure
CREATE PROCEDURE uspGetContact @LastName NVARCHAR(50), @ContactID INT output AS SELECT TOP 1 @ContactID = c.ContactID FROM HumanResources.Employee a INNER JOIN HumanResources.EmployeeAddress b ON a.EmployeeID = b.EmployeeID INNER JOIN Person.Contact c ON a.ContactID = c.ContactID INNER JOIN Person.Address d ON b.AddressID = d.AddressID WHERE c.LastName = @LastName

Step-2 After creating a stored procedure, run the below block of code. This will execute the above stored procedure and if the ContactID has a value it will also return the person and address info
DECLARE @ContactID INT SET @ContactID = 0 EXEC uspGetContact @LastName='Smith', @ContactID=@ContactID OUTPUT IF @ContactID <> 0 BEGIN SELECT ContactID, FirstName, LastName FROM Person.Contact WHERE ContactID = @ContactID SELECT d.AddressLine1, d.City, d.PostalCode FROM HumanResources.Employee a INNER JOIN HumanResources.EmployeeAddress b ON a.EmployeeID = b.EmployeeID INNER JOIN Person.Contact c ON a.ContactID = c.ContactID INNER JOIN Person.Address d ON b.AddressID = d.AddressID WHERE c.ContactID = @ContactID END

No comments:

Post a Comment