Hi
In below code i am getting Column Max Value from a table. I want that at same time 2 User should not be able to access same value
using (SqlConnection con0 = new SqlConnection(Common.CommonFunction.cnn_Live))
{
SqlCommand cmd0 = new SqlCommand("sp_MaxDocEntry", con);
cmd0.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@TableName", SqlDbType.VarChar).Value = "Department";
SqlParameter successParam1 = cmd.Parameters.Add("@Success", SqlDbType.Bit);
successParam1.Direction = ParameterDirection.Output;
SqlParameter DocEntry = cmd.Parameters.Add("@DocEntry", SqlDbType.Int);
DocEntry.Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
bool success1 = (bool)successParam1.Value;
if (success1)
{
cmd.Parameters.AddWithValue("@DocEntry", SqlDbType.Int).Value = successParam0;
int MaxDocEntry = Convert.ToInt32(DocEntry.Value);
}
else
{
ShowMessage("", success1.ToString(), "error");
}
}
Thanks
Naimish MakwanaPosted Sep 2, 2024, 5:45 AM
The table will be unlocked as soon as the transaction is completed. In the provided code, this happens when the
transaction.Commit()method is called. If an error occurs, thetransaction.Rollback()method will be called, which also releases the lock.Here’s a brief overview of the process:
TABLOCKXhint ensures the table remains locked during the execution of the stored procedure.transaction.Commit()is called, indicating the transaction is successfully completed.transaction.Rollback()is called, which also releases the lock.This ensures that the table is only locked for the duration of the transaction, preventing other users from accessing the same value simultaneously.
Thanks
Naimish MakwanaPosted Sep 2, 2024, 6:14 AM
Please check answer here
https://www.c-sharpcorner.com/Forums/error-sharp160conversion-failed-when-converting-the-varchar-value
Ramco RamcoPosted Sep 2, 2024, 6:09 AM
Hi naimish
What will be the value if there is no record. I want if there is no record @Docentry value should be 1
Thanks
Ramco RamcoPosted Sep 2, 2024, 5:26 AM
Hi Naimish
When the table will get unlock
Thanks
Naimish MakwanaPosted Sep 2, 2024, 5:19 AM
To ensure that two users do not access the same value simultaneously, you can use SQL Server’s locking mechanisms. One way to achieve this is by using the
TABLOCKXhint, which locks the entire table during the transaction. This will prevent other users from accessing the table until the transaction is complete.Here’s how you can modify your stored procedure to include the
TABLOCKXhint:In your C# code, make sure to handle the transaction properly:
In this version:
TABLOCKXhint to lock the entire table.This approach ensures that only one user can access the maximum document entry at a time, preventing concurrent access issues. Thanks