上次写这本书的书评的时候看到了第八章触发器。这几天看了后面几章:事务、错误处理、Service Broker,继续抄录:
1:sql server不支持真正意义上的嵌套事务。当你在事务内提交一个rollback tran,sql server回滚最外层begin tran之后的所有操作。
2:sql server支持保存点,它允许你撤销事务中的部分操作。
3:同一级别无法捕获解析/编译错误(例如引用的对象不存在),及时调用的代码包含在try块。但调用堆栈中的上一级可以捕获该错误。所以,在存储过程中封装可能发生错误的代码,并在try块中调用存储过程是一项不错的实践。
4:一个存储过程中的错误处理的例子,亮点是在存储过程中判断是否处于嵌套事务中,并根据结果在发生错误后采取不同的措施。
IF OBJECT_ID('dbo.usp_AddEmp') IS NOT NULL
DROP PROC dbo.usp_AddEmp;
GO
CREATE PROC dbo.usp_AddEmp
@empid AS INT, @empname AS VARCHAR(25), @mgrid AS INT
AS
-- Save tran count aside
DECLARE @tc AS INT;
SET @tc = @@trancount;
-- If tran was already active, create a savepoint
IF @tc > 0
SAVE TRAN S1;
-- If tran was not active, open a new one
ELSE
BEGIN TRAN
BEGIN TRY;
-- Modify data
INSERT INTO dbo.Employees(empid, empname, mgrid)
VALUES(@empid, @empname, @mgrid);
-- If proc opened the tran, it's responsible for committing it
IF @tc = 0
COMMIT TRAN;
END TRY
BEGIN CATCH
PRINT 'Error detected.';
PRINT CASE XACT_STATE()
WHEN 0 THEN 'No transaction is open.'
WHEN 1 THEN 'Transaction is open and committable.'
WHEN -1 THEN 'Transaction is open and uncommittable.'
END;
-- Proc opened tran
IF @tc = 0
BEGIN
-- Can react differently based on tran state (XACT_STATE)
-- In this case, say we just want to roll back
IF XACT_STATE() <> 0
BEGIN
PRINT 'Rollback of tran opened by proc.';
ROLLBACK TRAN
END
END
-- Proc didn't open tran
ELSE
BEGIN
IF XACT_STATE() = 1
BEGIN
PRINT 'Proc was invoked in an open tran. Roll back only proc''s activity.';
ROLLBACK TRAN S1
END
ELSE IF XACT_STATE() = -1
PRINT 'Proc was invoked in an open tran, but tran is uncommittable. Deferring
exception handling to caller.'
END
-- Raise error so that caller will determine what to do with
-- the failure in the proc
DECLARE
@ErrorMessage NVARCHAR(400),
@ErrorSeverity INT,
@ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH
GO
5:Service Broker也许是Microsoft SQL Server 2005中功能最强大、最不被熟知的新功能。
6:Service Broker把会话定义为会话端点之间的可靠的、顺序的、异步的信息交换。
7:编写异步消息应用程序最困难的是处理多个应用程序或多个线程从一个队列中同时获取消息。Service Broker通过使用会话组锁解决该问题。