Design a SQL Stored Procedure with Error Handling and Optimization

Generate a robust SQL stored procedure with transaction management, error logging, performance tuning, and security best practices.

๐Ÿ“ The Prompt

Write a SQL stored procedure named `[PROCEDURE_NAME]` for a [DATABASE_ENGINE] database (e.g., SQL Server, PostgreSQL, MySQL) that performs the following business operation: [BUSINESS_OPERATION_DESCRIPTION]. The procedure operates on the following tables: - [TABLE_1_NAME]: [TABLE_1_DESCRIPTION] (key columns: [TABLE_1_COLUMNS]) - [TABLE_2_NAME]: [TABLE_2_DESCRIPTION] (key columns: [TABLE_2_COLUMNS]) - [TABLE_3_NAME] (optional): [TABLE_3_DESCRIPTION] (key columns: [TABLE_3_COLUMNS]) Detailed Requirements: 1. **Input Parameters**: - [PARAM_1_NAME] [PARAM_1_DATATYPE] โ€” [PARAM_1_DESCRIPTION] - [PARAM_2_NAME] [PARAM_2_DATATYPE] โ€” [PARAM_2_DESCRIPTION] - [PARAM_3_NAME] [PARAM_3_DATATYPE] (optional, default [DEFAULT_VALUE]) โ€” [PARAM_3_DESCRIPTION] Include input validation for all parameters at the beginning of the procedure. Return meaningful error messages for invalid inputs. 2. **Output**: The procedure should return [OUTPUT_DESCRIPTION] (e.g., a result set, output parameters, or a status code with a message). Define output parameters: [OUTPUT_PARAM_NAME] [OUTPUT_PARAM_TYPE]. 3. **Business Logic**: Implement the following steps in order: - Step 1: [STEP_1_DESCRIPTION] - Step 2: [STEP_2_DESCRIPTION] - Step 3: [STEP_3_DESCRIPTION] Include conditional logic where [CONDITION_DESCRIPTION]. 4. **Transaction Management**: Wrap all data-modifying operations in an explicit transaction. Implement proper COMMIT on success and ROLLBACK on any failure. Handle nested transaction scenarios if applicable. 5. **Error Handling**: Use TRY...CATCH (SQL Server), BEGIN...EXCEPTION (PostgreSQL), or DECLARE HANDLER (MySQL) blocks. Log errors to an `[ERROR_LOG_TABLE]` table with columns: error_id, procedure_name, error_message, error_severity, error_timestamp, input_parameters_json. Re-raise critical errors after logging. 6. **Performance Optimization**: - Add index recommendations as comments for queries that filter or join on specific columns - Use SET NOCOUNT ON (SQL Server) or equivalent to reduce network overhead - Avoid cursors; use set-based operations wherever possible - Include query execution hints or temp table strategies if the data volume exceeds [EXPECTED_ROW_COUNT] rows 7. **Security**: Apply the principle of least privilege. Include GRANT/REVOKE statements for [ROLE_NAME]. Prevent SQL injection by using parameterized logic only. 8. **Documentation**: Add a header comment block with: procedure name, author placeholder, creation date placeholder, description, parameter descriptions, change log template, and a sample EXEC/CALL statement. Provide the complete CREATE PROCEDURE script, followed by the error log table DDL, recommended indexes, permission grants, and 3 sample execution calls demonstrating normal use, edge case, and error scenario.

๐Ÿ’ก Tips for Better Results

Always specify your exact DATABASE_ENGINE โ€” SQL Server, PostgreSQL, and MySQL have significantly different stored procedure syntax and error handling patterns. Describe your business operation with concrete data flow: what gets read, what gets inserted/updated/deleted, and what conditions trigger different outcomes. Include EXPECTED_ROW_COUNT estimates so the AI can recommend appropriate temp table strategies, batch processing, or indexing for your data scale.

๐ŸŽฏ Use Cases

Database developers and DBAs who need to implement complex business logic at the database layer with enterprise-grade error handling, audit logging, and performance considerations.

๐Ÿ”— Related Prompts

๐Ÿ’ป Coding beginner

Explain Code Like Im a Beginner

Get any code explained in plain English with line-by-line breakdowns, analogies, and learning suggestions.

๐Ÿ’ป Coding beginner

Debug My Code and Explain the Fix

Get your code debugged with clear explanations of what went wrong and why, plus the corrected version.

๐Ÿ’ป Coding intermediate

Write Unit Tests for My Code

Generate thorough unit tests covering edge cases, error handling, and both positive and negative scenarios.

๐Ÿ’ป Coding intermediate

Convert Code Between Languages

Convert code between any programming languages while maintaining idiomatic patterns and best practices.

๐Ÿ’ป Coding intermediate

Write a REST API Endpoint

Generate production-ready REST API endpoints with validation, error handling, and documentation.

๐Ÿ’ป Coding advanced

Create a GitHub Actions CI/CD Workflow for Automated Testing and Deployment

Generate a complete GitHub Actions CI/CD workflow with build, test, deploy, and notification jobs for your project.