在SQL Server 2016中。 我创建了一个具有绑定规则的用户定义数据类型的列。 T-SQL脚本如:
CREATE RULE [dbo].[R_typeYesNo]
AS @column IN ('Y', 'N')
GO
CREATE TYPE [dbo].[typeYesNo]
FROM VARCHAR (1) NULL
GO
EXECUTE sp_bindrule [R_typeYesNo], [typeYesNo]
GO
CREATE TABLE dbo.MyRuleTable (
ID int identity,
ACTIVEYN [dbo].[typeYesNo] NULL,
CONSTRAINT [PK_MyRuleTable] PRIMARY KEY CLUSTERED ([ID] ASC)
)
GO
INSERT INTO dbo.MyRuleTable(ACTIVEYN)
VALUES('A')
GO
-- Exception here
DROP TABLE dbo.MyRuleTable;
DROP TYPE [dbo].[typeYesNo];
DROP RULE [dbo].[R_typeYesNo];
GO
插入错误值后,规则检查将返回异常消息:
消息513,级别16,状态0,行20列插入或更新 与之前的CREATE RULE语句强加的规则冲突。该 声明被终止。冲突发生在数据库'DB1'中, 表'dbo.MyRuleTable',列'ACTIVEYN'。
可以,可以自定义消息吗?
答案 0 :(得分:0)
为您的规则
创建自定义错误消息EXEC sp_addmessage
500021,
10,
'This is a custom error message for MyRule'
使用CATCH
或RAISERROR
THROW
块中使用它
BEGIN try
-- Exception here
END try
BEGIN catch
IF Error_message() LIKE '%MyRuleTable%'
BEGIN
RAISERROR (500021,10,1)
END
ELSE
BEGIN
DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
DECLARE @ErrorState INT = ERROR_STATE();
RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
END
END catch