Explains how to detect, raise, and fix frequent SQL Server errors with TRY...CATCH and RAISERROR, using PostgreSQL-friendly syntax and examples.
Duplicate keys, constraint violations, divide-by-zero, and conversion failures dominate production incidents. They usually surface during INSERT, UPDATE, or aggregate calculations.
Wrap risky statements in TRY. On failure, control jumps to CATCH, where system functions like ERROR_NUMBER() expose details. This prevents session termination and lets you log or compensate.
Use BEGIN TRY / BEGIN CATCH blocks followed by END TRY / END CATCH. Inside CATCH, query ERROR_MESSAGE(), ERROR_SEVERITY(), and ERROR_STATE().
RAISERROR sends user-defined messages back to the client or calling procedure. Pair it with TRY...CATCH to surface meaningful diagnostics.
Supply a message string or message ID, severity (0-25), and state (1-255). Use WITH NOWAIT to flush output immediately.
The sample procedure inserts a new order, rescues violation 2627, rolls back, and raises a custom message so the application responds gracefully.
Validate inputs, check existence with IF NOT EXISTS, use TRY_CAST over CAST, and keep constraints explicit. Log errors into a dedicated table for later analysis.
Don’t swallow errors without re-throwing them. Avoid generic severity levels; inaccurate severity misleads monitoring tools.
Yes, it works from SQL Server 2005 onward. For SQL 2000, wrap statements in @@ERROR-based checks instead.
RAISERROR is still supported but THROW (SQL 2012+) is preferred for new code because it preserves the original stack and error state.
Create a table (e.g., ErrorLog) and INSERT rows inside the CATCH block capturing ERROR_NUMBER(), ERROR_MESSAGE(), and GETDATE().