user9342687
user9342687

Reputation:

Rollback and notify if something going wrong in sql transaction

Had a code that performed the transaction in windows forms via SqlTransaction and loaded the table with the database. If there was an error, it was simply output in the MessageBox.Show(ex.Message);. However, now it is necessary to process the data on the server side of the database, in the form of a procedure. But how do I inform the user if the data was incorrect in the transaction into application?

ALTER PROCEDURE [dbo].[addPacient]
    @name NVARCHAR(20),
    @surname NVARCHAR(20),
    @middle NVARCHAR(20),
    @passport NCHAR(10),
    @address NVARCHAR(20),
    @age INT,
    @name_diagnoz NVARCHAR(30),
    @stage CHAR(1)
AS
BEGIN TRAN  
    BEGIN TRY
        INSERT INTO Pacient(Name, Surname, Middle_name, Column__Passport,
                            Legal_address_Clinic, Age, id_diagnoz)
        VALUES (@name, @surname, @middle, @passport, 
                @address, @age, 
                (SELECT id_diagnoz FROM Diagnoz 
                 WHERE Name_diagnoz = @name_diagnoz and Stage = @stage))
    END  TRY
    BEGIN CATCH
        ROLLBACK TRAN

        RETURN
    END CATCH   
COMMIT TRAN

How it's being called:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand("addPacient", connection);
    command.CommandType = CommandType.StoredProcedure;

    command.Parameters.AddWithValue("@name", txtName.Text);
    command.Parameters.AddWithValue("@surname",  txtSurname.Text);
    command.Parameters.AddWithValue("@middle",  txtMiddle.Text);
    command.Parameters.AddWithValue("@passport",  mskPassport.Text);
    command.Parameters.AddWithValue("@address",  cbAddres.Text);
    command.Parameters.AddWithValue("@age",  cbAge.Text);
    command.Parameters.AddWithValue("@name_diagnoz", cbxNameDiagnoz.Text);
    command.Parameters.AddWithValue("@stage", cbxStage.Text);

    connection.Open();

    using (SqlDataReader dr = command.ExecuteReader())
    {
        while (dr.Read())
        {
            int intColumn = dr.GetInt32(dr.GetOrdinal("intColumnName"));
            string stringColumn = dr.GetString(dr.GetOrdinal("stringColumnName"));
        }
    }
}

Upvotes: 0

Views: 493

Answers (1)

Dan Guzman
Dan Guzman

Reputation: 46203

There is no need for an explict transaction in your current code; a single statement autocommit transaction will provide all-none and raise an error by default. The T-SQL TRY/CATCH does not provide value in this case so you can simply use:

ALTER PROCEDURE [dbo].[addPacient]
    @name NVARCHAR(20),
    @surname NVARCHAR(20),
    @middle NVARCHAR(20),
    @passport NCHAR(10),
    @address NVARCHAR(20),
    @age INT,
    @name_diagnoz NVARCHAR(30),
    @stage CHAR(1)
AS
INSERT INTO Pacient(Name, Surname, Middle_name, Column__Passport,
    Legal_address_Clinic, Age, id_diagnoz)
VALUES (@name, @surname, @middle, @passport, 
    @address, @age, 
        (SELECT id_diagnoz FROM Diagnoz 
    WHERE Name_diagnoz = @name_diagnoz and Stage = @stage));
GO

If you have multiple statements that perform data modifications within an explict T-SQL transaction, make sure you include SET XACT_ABORT ON in the proc code to ensure the transaction is automatically rolled back in case of a client timeout (where the CATCH block will not execute). I suggest this error handling pattern in multi-statement procs:

ALTER PROCEDURE [dbo].[addPacient]
    @name NVARCHAR(20),
    @surname NVARCHAR(20),
    @middle NVARCHAR(20),
    @passport NCHAR(10),
    @address NVARCHAR(20),
    @age INT,
    @name_diagnoz NVARCHAR(30),
    @stage CHAR(1)
AS
SET XACT_ABORT ON;
BEGIN TRY
    BEGIN TRAN;
    INSERT INTO Pacient(Name, Surname, Middle_name, Column__Passport,
        Legal_address_Clinic, Age, id_diagnoz)
    VALUES (@name, @surname, @middle, @passport, 
        @address, @age, 
            (SELECT id_diagnoz FROM Diagnoz 
        WHERE Name_diagnoz = @name_diagnoz and Stage = @stage));
    --other data modification statements
    COMMIT;
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK;
    THROW;
END CATCH;
GO

Also, it's best to avoid AddWithValue and pass strongly typed parameters. This will improve cache reuse on the server side and provides other benefits too.

try
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    using (SqlCommand command = new SqlCommand("addPacient", connection))
    {
        command.CommandType = CommandType.StoredProcedure;

        command.Parameters.Add("@name", SqlDbType.NVarChar, 20).Value = txtName.Text;
        command.Parameters.Add("@surname", SqlDbType.NVarChar, 20).Value = txtSurname.Text;
        command.Parameters.Add("@middle", SqlDbType.NVarChar, 20).Value  = txtMiddle.Text;
        command.Parameters.Add("@passport", SqlDbType.NChar, 10).Value = mskPassport.Text;
        command.Parameters.Add("@address", SqlDbType.NVarChar, 20).Value = cbAddres.Text;
        command.Parameters.Add("@age", SqlDbType.Int, 20).Value = int.Parse(cbAge.Text);
        command.Parameters.Add("@name_diagnoz", SqlDbType.NVarChar, 30).Value = cbxNameDiagnoz.Text;
        command.Parameters.Add("@stage", SqlDbType.Char, 1).Value = cbxStage.Text;

        connection.Open();

        using (SqlDataReader dr = command.ExecuteReader())
        {
            while (dr.Read())
            {
                int intColumn = dr.GetInt32(dr.GetOrdinal("intColumnName"));
                string stringColumn = dr.GetString(dr.GetOrdinal("stringColumnName"));
            }
        }
    }
}
catch (Exception ex)
{
    MessageGox.Show(ex.Message);
}

Upvotes: 1

Related Questions