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?

[SQLServer]ストアドプロシージャの作成_1

Last updated at Posted at 2024-06-24

1. サンプルテーブルの作成

CREATE_TABLE_Customers.sql
--顧客テーブル
CREATE TABLE Customers (
    CustomerID INT IDENTITY(1,1) PRIMARY KEY,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    Email NVARCHAR(100),
    Phone NVARCHAR(20),
    CreatedDate DATETIME DEFAULT GETDATE(),
    ModifiedDate DATETIME DEFAULT GETDATE()
);

2. ストアドプロシージャの作成

CREATE_PROCEDURE_usp_AddOrUpdateCustomer.sql
CREATE PROCEDURE usp_AddOrUpdateCustomer
    @CustomerID INT = NULL,
    @FirstName NVARCHAR(50),
    @LastName NVARCHAR(50),
    @Email NVARCHAR(100),
    @Phone NVARCHAR(20)
AS
BEGIN
    SET NOCOUNT ON;

    IF @CustomerID IS NULL
    BEGIN
        -- 新しい顧客を追加
        INSERT INTO Customers (FirstName, LastName, Email, Phone)
        VALUES (@FirstName, @LastName, @Email, @Phone);

        PRINT 'New customer added successfully.';
    END
    ELSE
    BEGIN
        -- 既存の顧客情報を更新
        UPDATE Customers
        SET FirstName = @FirstName,
            LastName = @LastName,
            Email = @Email,
            Phone = @Phone,
            ModifiedDate = GETDATE()
        WHERE CustomerID = @CustomerID;

        IF @@ROWCOUNT = 0
        BEGIN
            PRINT 'Customer not found.';
        END
        ELSE
        BEGIN
            PRINT 'Customer updated successfully.';
        END
    END
END;

3. ストアドプロシージャの使用例

EXEC_usp_AddOrUpdateCustomer_C.sql
--新しい顧客を追加する
EXEC usp_AddOrUpdateCustomer
    @FirstName = 'John',
    @LastName = 'Doe',
    @Email = 'john.doe@example.com',
    @Phone = '123-456-7890';
EXEC_usp_AddOrUpdateCustomer_U.sql
--既存の顧客情報を更新する
EXEC usp_AddOrUpdateCustomer
    @CustomerID = 1,  -- 更新したい顧客のID
    @FirstName = 'Jane',
    @LastName = 'Doe',
    @Email = 'jane.doe@example.com',
    @Phone = '098-765-4321';

4. Appendix(代表的なシステム変数)

システム変数 内容
@￰@￰ROWCOUNT 直前のステートメントで影響を受けた行数。
@￰@￰ERROR 直前のステートメントのエラーナンバー。正常終了の場合は0。
@￰@￰IDENTITY 同じセッション内で最後のINSERTによって生成されたID値。
@￰@￰TRANCOUNT 現在のセッションのトランザクションのネストレベル。
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?