MSSQL中的事务是否会锁定表?如果是这样,是在整个事务期间持有锁,还是仅在语句执行期间持有锁。下面是一个事务示例(忽略任何语法错误)
if ( sqlsrv_begin_transaction( $dbConnection ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$query = "INSERT INTO order_table (name,description,created_at) VALUES ('test_name','test_Transaction','some_date')";
$stmt1 = sqlsrv_query($dbConnection ,$query) or die('MSSQL error: ' . mssql_get_last_message());
$query = "INSERT INTO other_details_table (order_id,details) VALUES ('1234','order_details')";
$stmt2 = sqlsrv_query($dbConnection ,$query) or die('MSSQL error: ' . mssql_get_last_message());
sleep('20'); // used to delay the transaction time
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
当上面的事务正在进行时,我试图在表'order_ table‘中插入一条记录,但插入成功。如何锁定事务中的表,并在提交或回滚后解锁。
发布于 2016-08-03 20:36:28
事务将锁定一个表,直到事务被提交为止。即使查询结束,如果事务尚未提交或回滚,事务仍将保持打开状态。只要查询命中COMMIT或ROLLBACK,表就会被解锁。
但是,在您的代码中,我看不到您在哪里打开了事务,如果您没有打开事务,那么SQL Server将在提交和回滚时出错,因为如果您没有显式打开事务,MSSQL就足够智能地自行关闭事务。
https://stackoverflow.com/questions/38748750
复制