SQL Server Error Handling (THROW)
SQL Server Error Handling (THROW) is a SQL statement in the SQL Server Specific category. SQL Server 2012+: raises an exception. Can re-throw caught errors or create custom errors. The syntax is THROW [error_number, message, state];. It returns error raised/handled. A typical example: BEGIN TRY UPDATE employees SET salary = -100 WHERE id = 1; IF (SELECT salary FROM employees WHERE id = 1) < 0 THROW 50001, 'Salary cannot be negative', 1; END TRY BEGIN CATCH DECLARE @msg NVARCHAR(2048) = ERROR_MESSAGE(); INSERT INTO error_log (message, time) VALUES (@msg, GETDATE()); THROW; -- Re-throw original error END CATCH; -- Custom error with parameters: DECLARE @msg NVARCHAR(2048) = FORMATMESSAGE('Employee %d not found', @emp_id); THROW 50002,… A close relative is OUTPUT Clause, which sQL Server: returns values from DML statements (like PostgreSQL RETURNING). A close relative is STUFF(), which sQL Server: deletes a specified length of characters from a string and inserts another string at the start position.