我正在使用您创建新的.NET MVC应用程序时开箱即用的SimpleMembershipProvider,并且我希望允许管理员用户添加角色。出于学习目的,(我不知道这是否是正确的方法)我想将RoleName列的描述长度限制为15个字符,所以我写了这个事务:
create proc spInsertRole
(
@roleName varchar(50)
--really shouldn't be 50, but that's
--how I originally wrote my code
)
as
begin
set nocount on
begin try
begin tran
insert into dbo.webpages_Roles(RoleName)
values (@roleName)
commit transaction
end try
begin catch
select ERROR_MESSAGE() as ErrorMessage
if len(@roleName) > 15
rollback transaction
end catch
end
表上没有对RoleName长度的检查约束。这个proc会编译,但它也会让我添加一个大于15个字符的RoleName。我错过了什么,最好的方法是什么?
答案 0 :(得分:2)
在运行insert语句之前,应检查的长度。通过将长度检查放入catch块,您告诉程序只检查长度并在有其他错误情况时回滚。
(我的T-SQL生锈了,我没有要测试的数据库所以请在接受之前进行验证。另外,鉴于这些更改,您可能不再需要交易。)
create proc spInsertRole
(
@roleName varchar(50)
--really shouldn't be 50, but that's
--how I originally wrote my code
)
as
begin
set nocount on
begin try
begin tran
-- length check moved here. Raise error when > 15.
-- Severity (argument 2) needs to be higher than 10
-- to stop execution and trigger the catch block.
-- State (argument 3) is an arbitrary value between 0 and 255.
if len(@roleName) > 15
raiserror('Role name is too long.', 11, 5)
insert into dbo.webpages_Roles(RoleName)
values (@roleName)
commit transaction
end try
begin catch
select ERROR_MESSAGE() as ErrorMessage
-- length check was here. program will always roll back now.
rollback transaction
end catch
end
有关其工作原理的详情,请参阅RAISERROR。