Oh CRUD!

Writing Functions and Stored Procedures in SQL Server

Meghan Kwartler

IT Consultant

Why stored procedures for CRUD?

  • Decouples SQL code from other application layers

Chapter 3 N Tier architecture

Writing Functions and Stored Procedures in SQL Server

Why stored procedures for CRUD?

  • Decouples SQL code from other application layers

  • Improved security

Chapter 3 N Tier architecture

Writing Functions and Stored Procedures in SQL Server

Why stored procedures for CRUD?

  • Decouples SQL code from other application layers

  • Improved security

  • Performance

Chapter 3 N Tier architecture

Writing Functions and Stored Procedures in SQL Server

C for CREATE

CREATE PROCEDURE dbo.cusp_TripSummaryCreate (
  @TripDate as date, 
  @TripHours as numeric(18, 0)
) AS BEGIN INSERT INTO dbo.TripSummary(Date, TripHours) 
VALUES 
  (@TripDate, @TripHours) 
SELECT Date, TripHours 
FROM dbo.TripSummary 
WHERE Date = @TripDate END
Writing Functions and Stored Procedures in SQL Server

R for READ

CREATE PROCEDURE cusp_TripSummaryRead
    (@TripDate as date)
AS
BEGIN
SELECT Date, TripHours
FROM TripSummary
WHERE Date = @TripDate
END;
Writing Functions and Stored Procedures in SQL Server

U for UPDATE

CREATE PROCEDURE dbo.cusp_TripSummaryUpdate
    (@TripDate as date,
    @TripHours as numeric(18,0))
AS
BEGIN
UPDATE dbo.TripSummary
SET Date = @TripDate,
    TripHours = @TripHours
WHERE Date = @TripDate
END;
Writing Functions and Stored Procedures in SQL Server

D for DELETE

CREATE PROCEDURE cusp_TripSummaryDelete
    (@TripDate as date, 
     @RowCountOut int OUTPUT)
AS
BEGIN
DELETE
FROM TripSummary
WHERE Date = @TripDate

SET @RowCountOut = @@ROWCOUNT
END;
Writing Functions and Stored Procedures in SQL Server

Your turn for CRUD!

Writing Functions and Stored Procedures in SQL Server

Preparing Video For Download...