INSERT INTO T1 (xField) SELECT 7 AS xField WHERE (SELECT COUNT(*) FROM T1) = 0
基本上,如果一百万用户同时运行它,T1 中是否会出现不止一行?
Thread A: SELECT COUNT(*) FROM T1: 0
Thread B: SELECT COUNT(*) FROM T1: 0
Thread A: INSERT INTO T1...
Thread B: INSERT INTO T1...
还是保证永远不会发生,因为这只是一个声明?
如果这不安全,那么这样的事情呢?
表 T2(GoNorth 和 GoSouth 绝不能同时为 1):
ID GoNorth GoSouth
1 0 0
然后会发生这种情况:
User A: UPDATE T2 SET GoNorth = 1 WHERE GoSouth = 0
User B: UPDATE T2 SET GoSouth = 1 WHERE GoNorth = 0
Thread A: Find rows where GoSouth = 0
Thread B: Find rows where GoNorth = 0
Thread A: Found a row where GoSouth = 0
Thread B: Found a row where GoNorth = 0
Thread A: Setting GoNorth = 1 for the located row
Thread B: Setting GoSouth = 1 for the located row
结果:
ID GoNorth GoSouth
1 1 1
什么可以同时发生,什么不能同时发生的规则是什么?
我的数据库引擎是“Microsoft SQL Server 2008 R2 (SP2)”。