How to set isolation level on SqlCommand/SqlConnection initialized with no transaction

前端 未结 5 1488
忘了有多久
忘了有多久 2020-12-03 10:18

The following method is supposed to peroform a dirty read on an open connection. There are no transactions. Where do I set IsolationLevel?

public string DoDi         


        
相关标签:
5条回答
  • 2020-12-03 10:45

    In your Stored Procedure, for transact-sql use:

    SET TRANSACTION ISOLATION LEVEL read uncommitted    -- 0
    SET TRANSACTION ISOLATION LEVEL read committed     -- 1
    SET TRANSACTION ISOLATION LEVEL repeatable read    -- 2
    SET TRANSACTION ISOLATION LEVEL read serializable  -- 3
    
    0 讨论(0)
  • 2020-12-03 10:47

    Add another parameter to your stored procedure to indicate the isolation level you want the stored procedure to run with.

    IF @isolevel = 0 SET TRANSACTION ISOLATION LEVEL read uncommitted; ELSE

    Also I believe uncommitted needs two "t's" in it.

    0 讨论(0)
  • 2020-12-03 10:52

    Given you already have an existing connection (and possibly an existing transaction), I'd use a TransactionScope to control the isolation level of the child. This does a dirty read rowcount (I believe):

    using (var command = connection.CreateCommand())
    using(new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions{IsolationLevel = IsolationLevel.ReadUncommitted}))
    {
        command.CommandText = string.Format("select count(*) from {0}", tableName);
        return (int)command.ExecuteScalar();
    }
    
    0 讨论(0)
  • 2020-12-03 10:56

    If you don't want to do transactions, you can set it once when you open the connection and it will remain at that setting until you change it. So just do:

    connection.BeginTransaction(IsolationLevel.ReadUncommitted).Commit();
    

    Probably not the best for your specific case, since you are opening the connection, using it, and throwing it away, but I wanted to put this answer in for anyone with a longer-lived connection.

    0 讨论(0)
  • 2020-12-03 11:05

    On the BeginTransaction method: (MSDN link)

    And if you just want to use hints in your SP at the table level, use WITH(NOLOCK) - but use at your own risk.

    0 讨论(0)
提交回复
热议问题