BEGIN TRANSACTION
	BEGIN TRY
		-- YOUR SQL
		COMMIT
	END TRY
	BEGIN CATCH
		ROLLBACK
	END CATCH

  以上代码是在SQL SERVER 2008 中执行的.

  在使用了TRY CATCH之后, 只要出现异常就会跑CATCH里面回滚. 代码更清晰了更像我熟知的C#异常处理.

posted @ 2011-11-15 18:52 Orange Cheng 阅读(120) 评论(3) 编辑

MSDN上定义:事务是单个的工作单元。如果某一事务成功,则在该事务中进行的所有数据修改均会提交,成为数据库中的永久组成部分。如果事务遇到错误且必须取消或回滚,则所有数据修改均被清除。

  当前有张账户表Account ,字段 AccountID和Balance,Balance存在一个check( balance>=0), 数据 a,100; b,100。模拟银行转账的话,需要从a从扣除150,同时b中增加150。在sql

中实现都是通过update就行了。

update Account set balance=balance+150 where accountid='b'

update Account set balance=balance-150 where accountid='a'

但是,如果updateb时出错, a的balance会小于0 这样的话造成 a,100; b,250 。明显出错。使用事务的话如果存在错误会回滚到事务的开始

declare @op1 int
,
@op2 int
set @op1=0
Set @op2=0
begin transaction
update account set balance=balance+200 where accountid='b'
set @op1=@@ERROR
update account set balance=balance-200 where accountid='a'
set @op2=@@ERROR
if(@op1>0 or @op2>0)
rollback
else
commit

 这样的话需要在对每个sql语句执行时写句 x= @@ERROR

 并在最后通过判断每个sql执行是否错误来决定提交或回滚

其实,这样也行:

begin transaction
set xact_abort on
update account set balance=balance+200 where accountid='b'
update account set balance=balance-200 where accountid='a'
commit
 使用set xact_abort  on msdn解释: 指定当 Transact-SQL 语句出现运行时错误时,SQL Server 是否自动回滚到当前事务。
好了, 这样在出错时,自动回滚到事务开始处。在C#中可以使用try...catch 块,对工作单元中执行的SqlCommand的事务都制定
好一个,在catch中使用事务的回滚方法(C#代码部分我没试过,只是想当然)
posted @ 2011-07-05 19:07 Orange Cheng 阅读(516) 评论(0) 编辑
  在ASP.NET WebSite中,我们一般将公共的方法写到App_Code的类中去达到一种封装和复用。在MVC3中存在helper语法可以达到同样的目的。
  先看试图View下 Share文件夹中_Layout.cshtml:
 
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
     
      head部分对Css和Script文件的引用,其中Url.Content()将相对路径转为应用程序的绝对路径,和Server.MapPath()类似。使用helper语法如下:
@Css("Site.css")
@Script(
"jquery-1.5.1.min.js")
@helper Script(
string scriptName)
{
<script src="@Url.Content("~/Scripts/" + scriptName)" type="text/javascript"></script>
}
@helper Css(
string cssName)
{
<link href="@Url.Content("~/Content/"+cssName)" rel="stylesheet" type="text/css" />
}
       在项目下新建app_code文件夹,在app_code中新建一个视图文件Content.cshtml,删除里面的Code,并将原Layout.cshtml中的helper部分copy
到Content.cshtml下,这是发现Url缺少引用声明。添加@using System.Web.Mvc ,并添加一个的helper参数,如下:
  
@using System.Web.Mvc
@helper Script(string scriptName,UrlHelper Url)
    {
    <script src="@Url.Content("~/Scripts/" + scriptName)" type="text/javascript"></script>
}
@helper Css(string cssName, UrlHelper Url)
    {
    <link href="@Url.Content("~/Content/" + cssName)" rel="stylesheet" type="text/css" />
}
 
 这样Layout.cshtml页面就可以这样对Css和Scrpt引用了 (默认脚本放到Script文件夹中,样式文件放Content文件夹中)
<head>
    <title>@ViewBag.Title</title>
    @Content.Css("Site.css", Url)
    @Content.Script("jquery-1.5.1.min.js", Url)
</head>
 
 
 
 
posted @ 2011-07-05 18:24 Orange Cheng 阅读(760) 评论(2) 编辑