C# method to lock SQL Server table

前端 未结 4 1925
不知归路
不知归路 2021-02-14 03:31

I have a C# program that needs to perform a group of mass updates (20k+) to a SQL Server table. Since other users can update these records one at a time via an intranet website,

4条回答
  •  有刺的猬
    2021-02-14 03:54

    As someone has pointed out, the transaction doesn't seem to be used after being taken out.

    From the limited information we have on the app/purpose, it's hard to tell, but from the code snippet, it seems to me we don't need any locking. We are getting some data from source X (in this case _reader) and then inserting/updating into destination Y.

    All the validation happens against the source data to make sure it's correct, it doesn't seem like we're making any decision or care for what's in the destination.

    If the above is true then a better approach would be to load all this data into a temporary table (can be a real temp table "#" or a real table that we destroy afterwards, but the purpose is the same), and then in a single sql statement, we can do a mass insert/update from the temp table into our destination. Assuming the db schema is in decent shape, 20 (or even 30) thousand records should happen almost instantly without any need to wait for maintenance window or lock out users for extended periods of time

    Also to strictly answer the question about using transaction, below is a simple sample on how to properly use a transaction, there should be plenty of other samples and info on the web

    SqlConnection conn = new SqlConnection();
    SqlCommand cmd1 = new SqlCommand();
    SqlTransaction tran = conn.BeginTransaction();
    
    ...
    cmd1.Transaction = tran;
    ...
    tran.Commit();
    

提交回复
热议问题