- Owner 表包含列:owner_id, name - Cars 表包含列:owner_id(外键),brand - Books 表包含列:owner_id(外键),title, author 我的程序需要使用第三方库计算统计数据,例如“拥有 BMW 的车主中,同时也拥有《哈利·波特》的人数”。我想要同时从所有表中读取所有行,并在非 SQL 代码中进行分析。
我希望使用各自独立的“Select * From X”语句来读取所有表。由于一次大型联接将返回过多行(而不是 owner + cars + books),因此我不能使用一个大联接。Union 也不可行,因为这些表包含不同的列和不同的类型。
我已经设置好了……
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
但是我仍然遇到一些问题。
如果我通过运行两个线程来压力测试数据库,一个线程随机插入或删除,另一个线程读取,有时会出现不一致的结果,比如在读取Owners
和Cars
表之间,Cars
已经被删除了。
我有几个问题:
What's the proper way of preventing modification when reading from multiple tables one by one? No table must be modified until all have been read.
I'm using SQL Server 2005 (on network) and SQL Server 2005 Express (local). Can I explicitly get locks on multiple tables at the same time?
If I run against my local SQL Server Express database, I can't make it work no matter what I do. If I run against my networked SQL server 2005 database, I can make it work (with some effort). Does SQL Server Express support transaction isolation level SERIALIZABLE? I believe it should. The differences could be due to a slow network connection but I don't know.
On my local db, I can not prevent modification in between reads. That is, one thread is randomly deleting a random owner (first cars, then books, then owner) or inserting a new owner (insert owner, insert 2 cars, insert 2 books). Another thread is reading using:
Begin Tran Select owner_id From Owner Select owner_id, brand From Cars Select owner_id, title, author From Books Commit Tran
No matter what I do, sometimes I get an owner with zero cars or zero books. This should never happen since all inserts and deletes are in a single transaction. I seems like the express server doesn't lock Owner, Cars and Books statements at the same time.
On the networked SQL Server 2005, it works fine but it could be because of a slow connection and thus lower probability of simultaneous execution.
On my local db, I am starting every transaction with a dummy
Select
from all tables to prevent deadlocking. I don't understand why this prevents deadlocking but not modification of the tables. This is not necessary on the networked SQL Server 2005.
目前,我无法确定自己是否对事务隔离有误解,还是SQL Server Express和SQL Server 2005之间存在差异导致的问题。如果有任何帮助或见解,将不胜感激。