Delen via


@@ERROR (Transact-SQL)

Van toepassing op:SQL ServerAzure SQL DatabaseAzure SQL Managed InstanceAzure Synapse AnalyticsAnalytics Platform System (PDW)SQL Analytics-eindpunt in Microsoft FabricMagazijn in Microsoft FabricSQL-database in Microsoft Fabric

Geeft het foutnummer terug voor de laatste uitgevoerde Transact-SQL-instructie.

Transact-SQL syntaxis-conventies

Syntaxis

@@ERROR  

Retourtypen

integer

Opmerkingen

Geeft 0 terug als de vorige Transact-SQL-instructie geen fouten heeft gevonden.

Geeft een foutnummer terug als de vorige stelling een fout had gevonden. Als de fout een van de fouten in de sys.messages-catalogus was, bevat @@ERROR de waarde uit de kolom sys.messages.message_id voor die fout. Je kunt de tekst die gekoppeld is aan een @@ERROR foutnummer bekijken in sys.messages.

Omdat @@ERROR bij elke uitgevoerde instructie wordt gecleard en gereset, controleer je deze direct na de verificatie van de instructie, of sla je hem op als een lokale variabele die later kan worden gecontroleerd.

Gebruik de TRY... CATCH-constructie om fouten te behandelen. De TRY... De CATCH-constructie ondersteunt ook aanvullende systeemfuncties (ERROR_LINE, ERROR_MESSAGE, ERROR_PROCEDURE, ERROR_SEVERITY en ERROR_STATE) die meer foutinformatie teruggeven dan @@ERROR. PROBEREN... CATCH ondersteunt ook een ERROR_NUMBER functie die niet beperkt is tot het teruggeven van het foutnummer in de instructie direct na de instructie die een fout genereerde. Voor meer informatie, zie TRY...CATCH (Transact-SQL).

Voorbeelden

Eén. Met @@ERROR een specifieke fout detecteren

Het volgende voorbeeld wordt gebruikt @@ERROR om te controleren op een overtreding van controlebeperkingen (fout #547) in een UPDATE statement.

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. Het gebruik van @@ERROR om een procedure voorwaardelijk te beëindigen

Het volgende voorbeeld gebruikt IF...ELSE statements om na een DELETE statement in een stored procedure te testen@@ERROR. De waarde van de variabele @@ERROR bepaalt de retourcode die naar het aanroepende programma wordt gestuurd, wat het succes of falen van de procedure aangeeft.

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. Met @@ERROR @@ROWCOUNT

Het volgende voorbeeld gebruikt @@ERROR met @@ROWCOUNT om de werking van een UPDATE statement te valideren. De waarde van @@ERROR wordt gecontroleerd op enige aanwijzing van een fout en @@ROWCOUNT wordt gebruikt om te waarborgen dat de update succesvol is toegepast op een rij in de tabel.

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  

Zie ook

TRY... CATCH (Transact-SQL)
ERROR_LINE (Transact-SQL)
ERROR_MESSAGE (Transact-SQL)
ERROR_NUMBER (Transact-SQL)
FOUT_PROCÉDURE (Transact-SQL)
ERROR_SEVERITY (Transact-SQL)
FOUTTOESTAND (Transact-SQL)
@@ROWCOUNT (Transact-SQL)
sys.messages (Transact-SQL)
Naslaginformatie over fouten en gebeurtenissen (database-engine)