What Are SQL Stored Procedures?
A stored procedure is a compiled SQL program that performs a specific task like updating a table, retrieving data, or executing business logic. Think of it as a reusable function that lives in the database.
Why Use Them?
Encapsulation of logic
Performance boost (precompiled execution)
Easier maintenance and modularity
Security and access control
Creating Your First SQL Stored Procedure
Let’s create a simple procedure that updates a customer’s status.
IN CUST_ID INT,
IN NEW_STATUS CHAR(1)
)
LANGUAGE SQL
BEGIN
UPDATE CUSTOMER
SET STATUS = NEW_STATUS
WHERE ID = CUST_ID;
END;
Explanation:
INparameters are inputs.LANGUAGE SQLtells IBM i this is a native SQL procedure.BEGIN...ENDwraps the logic.
Calling the Procedure
You can call it from STRSQL, ACS Run SQL Scripts, or embedded in RPGLE:
Or from SQLRPGLE:
CALL UPDATE_CUSTOMER_STATUS(:CustomerID :NewStatus);
Adding Output Parameters
Let’s return a count of updated rows:
IN CUST_ID INT,
IN NEW_STATUS CHAR(1),
OUT ROWS_UPDATED INT
)
LANGUAGE SQL
BEGIN
UPDATE CUSTOMER
SET STATUS = NEW_STATUS
WHERE ID = CUST_ID;
SET ROWS_UPDATED = ROW_COUNT;
END;
Error Handling with DECLARE CONTINUE HANDLER
SET ROWS_UPDATED = -1;
This ensures your procedure doesn’t crash and burns gracefully.
Best Practices
Use meaningful procedure names (UPDATE_CUSTOMER_STATUS, not PROC1)
Document parameters and expected behavior
Keep procedures focused - one task per procedure
Use output parameters for feedback
Wrap logic in transactions if needed (COMMIT, ROLLBACK)
