Here is the stored procedure we did in class
Alter Procedure usp_NewSubscription
@CustLastName varchar(30),
@CustFirstName varchar(25),
@CustAddress varchar(100),
@CustCity varchar(50),
@CustState char(2),
@CustZipcode char(11),
@CustPhone char(10),
@Magazine varchar(100),
@SubscriptTypeID int,
@StartDate DateTime
As
Begin tran
--the as keyword starts the body of the procedure
--The first thing we will do is insert the customer
Begin try
--declare the customerid as a variable
Declare @CustID int
--test to see if customer exists by matching all the fields
if exists
(Select CustLastName, CustFirstName, CustAddress, CustCity, CustState, CustZipcode, CustPhone
From Customer
Where CustLastName=@CustLastName
And CustFirstName=@CustFirstName
And CustAddress=@CustAddress
And CustCity= @CustCity
And CustState= @CustState
And CustZipcode= @CustZipcode
And CustPhone=@CustPhone)
Begin --if customer does exist
--get the customer id of the existing customer
Select @CustID=Custid
From Customer
Where CustLastName=@CustLastName
And CustFirstName=@CustFirstName
And CustAddress=@CustAddress
And CustCity= @CustCity
And CustState= @CustState
And CustZipcode= @CustZipcode
And CustPhone=@CustPhone
End
Else --if it doesn't exist
Begin
--insert the customer
Insert into Customer(CustLastName, CustFirstName, CustAddress, CustCity, CustState, CustZipcode, CustPhone)
Values(
@CustLastName,
@CustFirstName,
@CustAddress,
@CustCity,
@CustState,
@CustZipcode,
@CustPhone)
--the user has provided all these values as parameters
--now we get the new CustID created by the insert
Set @CustID=@@Identity
End --end of else
--Next we look for the MagID using the magazine Name
Declare @MagID int
Select @MagID=Magid from Magazine where MagName=@Magazine
--with the magid and the subscription type (which was provided as a parameter
--we can look up the magdetid which is what we need for
--the insert into subscription
Declare @magDetID int
Select @magDetID=MagDetId
From MagazineDetail
where MagID=@MagID
And SubscriptTypeID=@SubscriptTypeID
--test to see if subscription exists or not
If not exists
(Select SubscriptionID from Subscription
Where MagDetID=@MagDetID
And CustID=@CustID
And SubscriptionEnd < GetDate())
Begin
--if it doesn't already exit insert the new subscription
Insert into Subscription
(CustID, MagDetID, SubscriptionStart, SubscriptionEnd)
Values
(@CustID, @MagDetID, @StartDate,
dbo.func_SubscriptionEndDate(@MagDetID, @StartDate))
end
--this will happen if there are no errors above
Commit tran
End try
Begin Catch
--if there are errors do this
Rollback tran
print error_message()
End Catch
No comments:
Post a Comment