日期:2014-05-18  浏览次数:20333 次

急--SQL2005存储过程和事务回滚Transact-SQL
SQL2005建立两个存储过程,无参数,有参数
1.当对一张表同时插入10条数据时,在插入到第9条时,报错; 
2.事务回滚 (之前插入数据取消)
3.抛出自定义异常 
4.C# 如何实现获取抛出的异常

------解决方案--------------------
SQL code

--just a example:
go
create proc pro_test
as
begin transaction 
insert table
select ......
if @@error<>0
begin
print ‘错误信息:'+ltrim(@@error)
rollback transaction
end
else
begin
commit transaction
end

------解决方案--------------------
可以在存储过程中加一个output的参数,让C#得到这个参数的实际值.
------解决方案--------------------
SQL code

go
if object_id('test','u')is not null
drop table test
go
create table test(
id int identity(1,1),
value varchar(10) check(isnumeric(value)=1)
)
go
if OBJECT_ID('pro_test')is not null
drop proc pro_test
go
create proc pro_test 
 @value1 varchar(10),
 @value2 varchar(10), 
 @value3 varchar(10),
 @ErrorMessage  varchar(2048) output
as
begin transaction
begin try
insert test(value)
select @value1 union all
select @value2 union all
select @value3
end try
begin catch
 SELECT @ErrorMessage=ERROR_MESSAGE()
end catch
if @ErrorMessage is not null 
begin
select @ErrorMessage as ENDMessage
rollback transaction 
end
else
begin
select '插入成功' as ENDMessage
commit transaction
end
--演示插入失败
go
declare @ErrorMessage varchar(2048)
exec pro_test '12345','af345','90dg',@ErrorMessage output  
/*
ENDMessage
INSERT 语句与 CHECK 约束"CK__test__value__02DD43D9"冲突。
该冲突发生于数据库"master",表"dbo.test", column 'value'。
*/

--演示插入成功
go
declare @ErrorMessage varchar(2048)
exec pro_test '12345','56324','8956',@ErrorMessage output  
/*
ENDMessage
插入成功
*/

select * from test

/*
id    value
1    12345
2    56324
3    8956
*/



--刚刚回来,写了一个例子,不知道符合你的要求么

------解决方案--------------------
写成存储过程
同时加上try catch