@@ERROR (Transact-SQL)

Si applica a:SQL Server database SQL di Azure Istanza gestita di SQL di Azure Azure Synapse Analytics AnalyticsPlatform System (PDW)SQL analytics endpoint in Microsoft FabricWarehouse in Microsoft Fabric

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 (12.x) e versioni precedenti, vedere la documentazione delle versioni precedenti.

Tipi restituiti

integer

Osservazioni:

Restituisce 0 se nell'istruzione Transact-SQL precedente non è stato rilevato alcun errore.

Restituisce un numero di errore se nell'istruzione precedente è stato rilevato un errore. Se l'errore è stato uno degli errori nella vista del catalogo sys.messages, @@ERROR contiene il valore della colonna sys.messages.message_id per tale errore. È possibile visualizzare il testo associato a un numero di errore @@ERROR in sys.messages.

Poiché @@ERROR viene cancellato e reimpostato su ogni istruzione eseguita, controllarlo immediatamente dopo la verifica dell'istruzione o salvarlo in una variabile locale che può essere verificata in un secondo momento.

Il costrutto TRY...CATCH viene utilizzato per la gestione degli errori. L'istruzione TRY... Il costrutto CATCH supporta anche funzioni di sistema aggiuntive (ERROR_LINE, ERROR_MESSAGE, ERROR_PROCEDURE, ERROR_edizione Standard VERITY e ERROR_STATE) che restituiscono più 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. Uso di @@ERROR per rilevare un errore specifico

Nell'esempio seguente si utilizza @@ERROR per rilevare una violazione di vincolo CHECK (errore numero 547) in un'istruzione UPDATE.

USE AdventureWorks2022;  
GO  
UPDATE HumanResources.EmployeePayHistory  
    SET PayFrequency = 4  
    WHERE BusinessEntityID = 1;  
IF @@ERROR = 547
    BEGIN
    PRINT N'A check constraint violation occurred.';
    END
GO  

B. Uso di @@ERROR per uscire in modo condizionale da una routine

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 AdventureWorks2022;  
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. Uso 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 AdventureWorks2022;  
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  

Vedi anche

PROVARE... CATCH (Transact-SQL)
ERROR_LINE (Transact-SQL)
ERROR_MESSAGE (Transact-SQL)
ERROR_NUMBER (Transact-SQL)
ERROR_PROCEDURE (Transact-SQL)
ERROR_edizione Standard VERITY (Transact-SQL)
ERROR_STATE (Transact-SQL)
@@ROWCOUNT (Transact-SQL)
sys.messages (Transact-SQL)
Riferimenti a errori ed eventi (motore di database)