0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQL Server のストアドプロシージャ 備忘録

Last updated at Posted at 2021-12-22

参考

テーブルの準備

DROP TABLE  IF EXISTS student_tb;
CREATE TABLE student_tb(
student_id INT,
first_name CHAR(20),
last_name CHAR(20),
birthday DATE,
gender CHAR(5)
);
student_id first_name last_name birthday gender
1 太郎 山田 1980/2/15 男性
2 花子 田中 1979/12/30 女性
3 優子 鈴木 1979/7/7 女性
4 孝雄 佐藤 1980/3/12 男性
5 弘樹 髙木 1979/4/5 男性
6 優佳 木村 1981/3/27 女性
DROP TABLE  IF EXISTS test_result_tb;
CREATE TABLE test_result_tb(
test_result_id INT,
test_id INT,
student_id INT,
score INT
);
test_result_id test_id student_id score
1 1 1 85
2 1 2 60
3 1 4 98
4 1 5 73
5 2 1 77
6 2 NULL NULL
7 2 3 92
8 2 4 81

ストアド作成

CREATE PROCEDURE uspStudentDelete
    @StudentID      INT,
    @ErrorMessage   NVARCHAR(100) OUT
AS
BEGIN
    IF EXISTS
        (SELECT *
         FROM   TestResult
         WHERE  StudentID = @StudentID)
       BEGIN
        SET @ErrorMessage = N'TestResult が存在するので削除できません。';
       END
    ELSE
       BEGIN
        DELETE
        FROM    Student
        WHERE   StudentID = @StudentID;
       END
END;
項目 説明 備考
@StudentID INT @パラメータ + 型 ストアド作成時はDECLEAR不要
NVARCHAR(100) OUT アウトプットパラメータの後ろには OUTPUT または OUT というキーワードをつける
END BEGIN...END構文 入れ子も可能
https://docs.microsoft.com/ja-jp/sql/t-sql/language-elements/begin-end-transact-sql?view=sql-server-ver15
SET @ErrorMessage SET 変数 = 代入

ストアドの呼び出し方

DECLARE @ErrorMessage NVARCHAR(100);

EXEC uspStudentDelete 6, @ErrorMessage OUTPUT;

PRINT @ErrorMessage;
項目 説明 備考
DECLARE DECLARE + 変数 + 型
EXEC EXECUTE または EXECで呼び出し
EXECUTE + ストアド + パラメータ

更新

  • ストアドを選択してModityをクリックする。
    image.png

  • ALTER PROCEDURE のステートメントがクエリー画面に出る。

  • 更新後、Execute する。

削除

DROP PROCEDURE uspStudentDelete;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?