事務,索引和視圖

來源:互聯網
上載者:User

 

>[1]事務

use studb
go
if exists (select * from sysobjects where name = 'bank')
drop table bank
go
create table bank
(
   customername  char(10),
   currentmoney  money
)
go
alter table bank
   add constraint ck_currentmoney check (currentmoney>=1)
go
insert into bank (customername,currentmoney) values ('張三',1000)
insert into bank (customername,currentmoney) values ('李四',1)
select * from bank
go

事務的屬性
1. 原子性
2. 一致性
3. 隔離性
4. 持久性

開始事務:begin transaction
提交事務:commit transaction
復原事務:rollback transaction

use studb
go
update bank set currentmoney = currentmoney - 1000 where customername = '李四'
set nocount on  -----不顯示受影響的行數資訊
print '查看轉帳事務前的餘額'
select * from bank
go
begin transaction
declare @errorsum int
set @errorsum = 0
update bank set currentmoney = currentmoney - 1000
where customername = '張三'
set @errorsum = @errorsum + @@error  -----累計是否有錯誤
update bank set currentmoney = currentmoney + 1000
set @errorsum = @errorsum + @@error
print '查看轉帳事務過程中的餘額'
select * from bank
if @errorsum<>0
  begin
    print '交易失敗,復原事務' 
    rollback transaction
  end 
else
  begin
    print '交易成功,提交事務,寫入硬碟,永久的儲存' 
    commit transaction
  end
go
print '查看轉帳事務後的餘額'
select * from bank
go

…………………………………………………………………………………………………………………………

……………

>[2]索引

use studb
go
if exists (select name from sysindexes where name = 'ix_stumarks_writtenexam')
drop index stumarks.ix_stumarks_writtenexam
create
 nonclustered index ix_stumarks_writtenexam
on stumarks(writtenexam)
with fillfactor = 30
go

select * from stumarks(index = ix_stumarks_writtenexam)
where writtenexam between 60 and 90

…………………………………………………………………………………………………………………………

……………

>[3]視圖

use studb
go
if exists (select * from sysobjects where name = 'view_stuinfo_stumarks')
drop view view_stuinfo_stumarks
go
create view view_stuinfo_stumarks
as
  select 姓名 = stuname,學號 = stuinfo.stuno,筆試成績 = writtenexam,機試成績 = labexam,平均

分 = (writtenexam+labexam)/2
  from stuinfo left join stumarks on stuinfo.stuno = stumarks.stuno
go
select * from view_stuinfo_stumarks

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.