26

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 DoDirtyRead(string storedProcName, SqlConnection connection)
{
    using (SqlCommand command = new SqlCommand(storedProcName, connection))
    {
        command.CommandType = CommandType.StoredProcedure;
        // HOW TO SET IsolationLevel to READ_UNCOMMITTED here?
        command.ExecuteNonQuery();
    }
}
4

5 に答える 5

23

トランザクションを実行したくない場合は、接続を開いたときに一度設定すれば、変更するまでその設定のままになります。だから、ただやってください:

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

接続を開いて使用し、破棄するため、特定のケースにはおそらく最適ではありませんが、接続の寿命が長い人のためにこの回答を入れたいと思いました。

于 2011-08-25T13:47:20.577 に答える
12

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.

于 2010-12-03T01:08:11.823 に答える
7

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
于 2010-12-03T01:21:46.097 に答える
7

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();
}
于 2013-06-15T00:33:18.157 に答える
0

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.

于 2017-09-29T16:21:44.343 に答える