@@ERROR (Transact-SQL)
Si applica a: SQL Server (tutte le versioni supportate) database SQL di Azure Istanza gestita di SQL di Azure
Azure Synapse Analytics Analytics
Platform System (PDW)
Restituisce il numero di errore per l'ultima istruzione Transact-SQL eseguita.
Convenzioni di sintassi Transact-SQL
Sintassi
@@ERROR
Nota
Per visualizzare la sintassi Transact-SQL per SQL Server 2014 e versioni precedenti, vedere Documentazione delle versioni precedenti.
Tipi restituiti
numero intero
Commenti
Restituisce 0 se l'istruzione Transact-SQL precedente non ha rilevato errori.
Restituisce un numero di errore se nell'istruzione precedente è stato rilevato un errore. Se l'errore rilevato è descritto nella vista del catalogo sys.messages, la funzione @@ERROR include il valore riportato nella colonna sys.messages.message_id per tale errore. È possibile esaminare il testo associato a un numero di errore di @@ERROR in sys.messages.
Poiché la funzione @@ERROR viene cancellata e reimpostata ogni volta che viene eseguita un'istruzione, è necessario controllarne il valore subito dopo l'esecuzione dell'istruzione da verificare oppure salvarla in una variabile locale che è possibile controllare in un secondo momento.
Il costrutto TRY...CATCH viene utilizzato per la gestione degli errori. Il costrutto TRY...CATCH supporta inoltre funzioni di sistema aggiuntive (ERROR_LINE, ERROR_MESSAGE, ERROR_PROCEDURE, ERROR_SEVERITY e ERROR_STATE) che restituiscono un maggior numero di informazioni sull'errore rispetto a @@ERROR. TRY...CATCH supporta anche una funzione ERROR_NUMBER che non si limita a restituire il numero di errore nell'istruzione immediatamente successiva a quella in cui è stato generato un errore. Per altre informazioni, vedere TRY... CATCH (Transact-SQL).
Esempi
R. Utilizzo di @@ERROR per individuare un errore specifico
Nell'esempio seguente si utilizza @@ERROR
per rilevare una violazione di vincolo CHECK (errore numero 547) in un'istruzione UPDATE
.
USE AdventureWorks2012;
GO
UPDATE HumanResources.EmployeePayHistory
SET PayFrequency = 4
WHERE BusinessEntityID = 1;
IF @@ERROR = 547
BEGIN
PRINT N'A check constraint violation occurred.';
END
GO
B. Utilizzo di @@ERROR per uscire da una procedura in modo condizionale
Nell'esempio seguente vengono usate istruzioni IF...ELSE
per testare @@ERROR
dopo un'istruzione DELETE
in una stored procedure. Il valore della variabile @@ERROR
determina il codice restituito inviato al programma chiamante per segnalare se la procedura ha avuto esito positivo o negativo.
USE AdventureWorks2012;
GO
-- Drop the procedure if it already exists.
IF OBJECT_ID(N'HumanResources.usp_DeleteCandidate', N'P') IS NOT NULL
DROP PROCEDURE HumanResources.usp_DeleteCandidate;
GO
-- Create the procedure.
CREATE PROCEDURE HumanResources.usp_DeleteCandidate
(
@CandidateID INT
)
AS
-- Execute the DELETE statement.
DELETE FROM HumanResources.JobCandidate
WHERE JobCandidateID = @CandidateID;
-- Test the error value.
IF @@ERROR <> 0
BEGIN
-- Return 99 to the calling program to indicate failure.
PRINT N'An error occurred deleting the candidate information.';
RETURN 99;
END
ELSE
BEGIN
-- Return 0 to the calling program to indicate success.
PRINT N'The job candidate has been deleted.';
RETURN 0;
END;
GO
C. Utilizzo di @@ERROR con @@ROWCOUNT
Nell'esempio seguente si utilizza @@ERROR
con @@ROWCOUNT
per verificare l'operazione di un'istruzione UPDATE
. Il valore di @@ERROR
viene controllato per verificare la presenza di errori, mentre la funzione @@ROWCOUNT
viene utilizzata per assicurare che l'aggiornamento di una riga della tabella sia stato eseguito correttamente.
USE AdventureWorks2012;
GO
IF OBJECT_ID(N'Purchasing.usp_ChangePurchaseOrderHeader',N'P')IS NOT NULL
DROP PROCEDURE Purchasing.usp_ChangePurchaseOrderHeader;
GO
CREATE PROCEDURE Purchasing.usp_ChangePurchaseOrderHeader
(
@PurchaseOrderID INT
,@BusinessEntityID INT
)
AS
-- Declare variables used in error checking.
DECLARE @ErrorVar INT;
DECLARE @RowCountVar INT;
-- Execute the UPDATE statement.
UPDATE PurchaseOrderHeader
SET BusinessEntityID = @BusinessEntityID
WHERE PurchaseOrderID = @PurchaseOrderID;
-- Save the @@ERROR and @@ROWCOUNT values in local
-- variables before they are cleared.
SELECT @ErrorVar = @@ERROR
,@RowCountVar = @@ROWCOUNT;
-- Check for errors. If an invalid @BusinessEntityID was specified,
-- the UPDATE statement returns a foreign key violation error #547.
IF @ErrorVar <> 0
BEGIN
IF @ErrorVar = 547
BEGIN
PRINT N'ERROR: Invalid ID specified for new employee.';
RETURN 1;
END
ELSE
BEGIN
PRINT N'ERROR: error '
+ RTRIM(CAST(@ErrorVar AS NVARCHAR(10)))
+ N' occurred.';
RETURN 2;
END
END
-- Check the row count. @RowCountVar is set to 0
-- if an invalid @PurchaseOrderID was specified.
IF @RowCountVar = 0
BEGIN
PRINT 'Warning: The BusinessEntityID specified is not valid';
RETURN 1;
END
ELSE
BEGIN
PRINT 'Purchase order updated with the new employee';
RETURN 0;
END;
GO
Vedere anche
TRY...CATCH (Transact-SQL)
ERROR_LINE (Transact-SQL)
ERROR_MESSAGE (Transact-SQL)
ERROR_NUMBER (Transact-SQL)
ERROR_PROCEDURE (Transact-SQL)
ERROR_SEVERITY (Transact-SQL)
ERROR_STATE (Transact-SQL)
@@ROWCOUNT (Transact-SQL)
sys.messages (Transact-SQL)
Guida di riferimento a errori ed eventi (Motore di database)