SQL 建立儲存過程PROCEDURE

景上發表於2016-05-28

1、建立儲存過程:

USE test2
GO
CREATE PROCEDURE FruitProce  -----檢視錶fruits的儲存過程;
AS
  SELECT * FROM fruits;
GO

--USE test2
--GO
CREATE PROCEDURE CountProce -------獲取表fruits的記錄數;
AS
  SELECT COUNT(*) FROM fruits; 
GO

EXEC FruitProce;   ------ 執行儲存過程:
EXEC CountProce;

這裡寫圖片描述

2、建立帶輸入引數的儲存過程:

CREATE PROCEDURE QueryById @js_ID INT
AS
  SELECT * FROM fruits WHERE f_id=@js_ID;
GO
--執行儲存過程:
EXEC QueryById 2; ------直接給出引數值,多個引數時,順序要對應;
EXEC QueryById @js_ID=2;--使用“引數名=引數值”;

這裡寫圖片描述

3、帶預設引數的儲存過程:

CREATE PROCEDURE QueryById1 @js_ID INT = 2
AS 
 SELECT * FROM fruits WHERE f_id=@js_ID;
GO

EXEC QueryById1;

這裡寫圖片描述

4、建立帶輸出引數的儲存過程:根據提供的id,返回其price;

CREATE PROCEDURE QueryById2 
@js_ID INT = 2,
@js_price FLOAT OUTPUT   ---如果忽略output,儲存過程會執行,但沒有返回值;
AS
  SELECT @js_price=fruits.f_price FROM fruits WHERE f_id=@js_ID;
GO

---呼叫QueryById2,將結果儲存到變數@js_price中;
DECLARE @js_price FLOAT, @js_ID INT = 2;
EXEC QueryById2 @js_ID,@js_price OUTPUT
  SELECT '該水果的價格為:'+LTRIM(STR(@js_price))+' .';
GO

這裡寫圖片描述

5、修改儲存過程:

ALTER  PROCEDURE CountProce
AS
   SELECT COUNT(*) AS NUM FROM fruits; 
GO

EXEC CountProce;

這裡寫圖片描述

6、檢視過程資訊:分別使用ONJECT_DEFINITION、sp_help、sp_helptext檢視;

SELECT OBJECT_DEFINITION(OBJECT_ID('CountProce'));
EXEC sp_help CountProce;
EXEC sp_helptext CountProce;

這裡寫圖片描述

7、重新命名儲存過程:

EXEC sp_rename 'CountProce1','CountProce';

8、刪除儲存過程:

DROP PROCEDURE FruitProce;

相關文章