มาใช้ EXEC กันเลย!

การเขียนฟังก์ชันและ Stored Procedures ใน SQL Server

Meghan Kwartler

IT Consultant

วิธีใช้ EXEC

  • ไม่มี output parameter หรือค่าที่ส่งคืน
  • เก็บค่าที่ส่งคืน
  • ใช้ output parameter
  • ใช้ output parameter และเก็บค่าที่ส่งคืน
  • เก็บ result set
การเขียนฟังก์ชันและ Stored Procedures ใน SQL Server

ไม่มี output parameter หรือค่าที่ส่งคืน

EXEC dbo.cusp_TripSummaryUpdate 
     @TripDate = '1/5/2017'
     @TripHours = '300'

ใช้ output parameter

DECLARE @RideHrs as numeric(18,0)

EXEC dbo.cuspSumRideHrsOneDay 
     @DateParm = '1/5/2017', 
     @RideHrsOut = @RideHrs OUTPUT
SELECT @RideHrs as TotalRideHrs
+--------------+
| TotalRideHrs |
|--------------+
| 77733        |
+--------------+
การเขียนฟังก์ชันและ Stored Procedures ใน SQL Server

ใช้ค่าที่ส่งคืน

Declare @ReturnValue as int

EXEC @ReturnValue = 
     dbo.cusp_TripSummaryUpdate 
     @TripDate = '1/5/2017', 
     @TripHours = 300

Select @ReturnValue as ReturnValue
+-------------+
| ReturnValue |
|-------------+
| 0           |
+-------------+

ใช้ค่าที่ส่งคืนและ output parameter

Declare @ReturnValue as int
Declare @RowCount as int

EXEC @ReturnValue = 
     dbo.cusp_TripSummaryDelete 
     @TripDate = '1/5/2017', 
     @RowCountOut = @RowCount OUTPUT

Select @ReturnValue as ReturnValue, 
     @RowCount as RowCount
+-------------+----------+
| ReturnValue | RowCount |
|-------------+----------|
| 0           | 1        |
+-------------+----------|
การเขียนฟังก์ชันและ Stored Procedures ใน SQL Server

EXEC และการเก็บ result set

DECLARE @TripSummaryResultSet as TABLE(
        TripDate date,
        TripHours numeric(18,0))

INSERT INTO @TripSummaryResultSet EXEC cusp_TripSummaryRead @TripDate = '1/5/2017'
SELECT * FROM @TripSummaryResultSet
+------------+-----------+
| TripDate   | TripHours |
|------------+-----------|
| 2017-01-05 | 200       |
+------------+-----------|
การเขียนฟังก์ชันและ Stored Procedures ใน SQL Server

ถึงเวลา EXEC Stored Procedure แล้ว!

การเขียนฟังก์ชันและ Stored Procedures ใน SQL Server

Preparing Video For Download...