0

I need a help. Let me first explain the scenario with a small sample.

Suppose I have a Students table with columns:

Id int(PK)  
Name varchar(200)  
Marks1 int  
Marks2 int  
Marks3 int  
TotalMarks int  
IsTotalCalculated bit  
InProcess bit

This table has huge number of records.

Now, I want to calculate the TotalMarks of each student and update the TotalMarks column.

Now coming to my C# Console App I am calling to stored procedures:

SP1 => I am fetching top two records at a time which has InProcess = 0 and IsTotalCalculated = 0, sets its InProcess = 1 and do the processing. (Has a SELECT and UPDATE)

SP2 => Finally again update these two rows which updates its IsTotalCalculated = 1 and InProcess = 0 (UPDATE)

Concern: My concern is as soon as I select the 2 rows for processing then any other Console App instance should not select these 2 rows for processing. What should I do?
Note: I have put the C# code of my two SPs in a TransactionBlock.

Thanks,

Justin Samuel

4

3 回答 3

1

如果 InProcess = 1 则您不能只检查 SP1 ,然后如果这是真的忽略其余部分,直到 InProcess 变为 0 ?

诀窍是在将 InProcess 更新为 1 时阻止任何读取。这可以通过 SET TRANSACTION ISOLATION LEVEL READ COMMITTED 来完成,它指定语句(在您的 SP 中)不能读取已修改但未由其他事务提交的数据。

希望这可以帮助。

于 2009-12-03T10:50:37.897 回答
1

你到底为什么要在 C# 中这样做?这非常适合 T-SQL!

 UPDATE 
     dbo.Students
 SET 
     TotalMarks = (some formula),
     IsTotalCalculated = 1
 WHERE 
     IsTotalCalulated = 0

一条 T-SQL 语句就完成了,不用担心事务范围和来回移动数据负载......

好的,所以如果你必须坚持你目前的方法 - 这就是你可以做的:

关注:我担心的是,一旦我选择了 2 行进行处理,那么任何其他控制台应用程序实例都不应该选择这 2 行进行处理。我应该怎么办?

“隐藏”表怎么样Students,例如不允许任何人访问它,而是在它上面使用一个视图,它只显示 InProcess = 0 的行?

CREATE VIEW dbo.StudentsView
AS
    SELECT (list of fields)
    FROM dbo.Students
    WHERE InProcess = 0

这样,任何读取学生的请求将始终只读取那些当前未处理的请求。

于 2009-12-03T10:51:34.570 回答
0

我确定您有理由按照自己的方式做事,但如果这是实际表格而不仅仅是说明性示例,那么您为什么不使用带有计算的 Total 列的视图呢?然后,您无需使用控制台应用程序处理行,也无需锁定任何行。

于 2009-12-03T10:28:26.777 回答