How to cast exception in SQL and treat in C#

Asked

Viewed 308 times

4

I’m creating procedures in an SQL Server database. To clear a brand, I first check if the brand is already tied to a product before deleting.

CREATE PROCEDURE SP_Delete_MarcasProdutos
@Id int
AS
BEGIN
    DECLARE @AUX int
    SET @AUX = (select top 1 p.Id from Produtos p where p.MarcaProduto_Id = @Id AND p.Excluido = 0)

    IF(@AUX IS NOT NULL)
        BEGIN
            PRINT 'Não foi possível excluir esta marca, pois ela possui relacionamentos com produtos ativos';
            THROW;
        END
    ELSE
        UPDATE MarcasProdutos SET Excluido = 1 WHERE Id = @Id
END

The procedure in If works? By releasing this exception, this will be the message captured by C#?

1 answer

6


You can use the RAISEERROR with a severity level of at least 10 (smaller numbers do not cause exception). This will produce an exception in C# that can be captured by SQLException.

  • It would be something like: "RAISEERROR('We could not exclude this brand because it has relationships with active products', 8)"?

  • Only if it’s 8, it won’t generate an exception in C#.

  • Aaah right, I’ll try here. Thank you!

  • @Davign You can see in detail here: https://msdn.microsoft.com/pt-br/library/ms164086.aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.