ข้าพเจ้าเชื่อว่าพระคุณของพระเจ้านั้นเพียงพอต่อชีวิตและครอบครัวของข้าพเจ้า

เกลือจืด
Location :


[ดู Profile ทั้งหมด]

ฝากข้อความหลังไมค์
Rss Feed
Smember
ผู้ติดตามบล็อก : 7 คน [?]




Group Blog
 
<<
มกราคม 2552
 123
45678910
11121314151617
18192021222324
25262728293031
 
22 มกราคม 2552
 
All Blogs
 
Friends' blogs
[Add เกลือจืด's blog to your web]
Links
 

 
ตัวอย่างการเขียน store procedure ของ MS SQL Server

ในตัวอย่างเป็นการสร้าง table ชื่อ abc เป็นการทดสอบง่าย
จากนั้นสร้าง store procedure สำหรับ add,update,delete ข้อมูล


-- check ว่ามี table นี้อยู่หรือไม่ ถ้ามี ให้ drop ก่อน
if exists(select name from sysobjects where id = object_id('abc'))
begin
print 'try to drop table abc'
drop table abc
end
go
-- สร้าง table abc
create table abc (
code char(2) not null,
description varchar(20) null,
active bit null default 0)
-- สร้าง unique index
create unique index uni_abc on abc(code)
-- ทดสอบ insert ข้อมูล
insert into abc values ('AA','TEST 1',1);
-- check ว่ามี proc นี้หรือไม่ ถ้ามี drop ก่อน
if exists(select name from sysobjects where id = object_id('proc_abcInsUpdDel'))
begin
print 'try to drop proc proc_abcInsUpdDel'
drop proc proc_abcInsUpdDel
end
go
-- สร้าง store proc insert/update/delete
create proc proc_abcInsUpdDel
@option tinyint,
@code char(2),
@description varchar(20)=null,
@active bit=null
as
if @active is null
select @active = 1
if @option = 1
begin
insert into abc(code,description,active) values (@code,@description,@active)
if @@error <> 0
begin
raiserror( 'proc_abcInsUpdDel:ไม่สามารถบันทึกข้อมูลได้',16,-1)
end
else
begin
print 'save complete'
end
end
if @option = 1
begin
insert into abc(code,description,active) values (@code,@description,@active)
if @@error <> 0
begin
raiserror( 'proc_abcInsUpdDel:ไม่สามารถบันทึกข้อมูลได้',16,-1)
end
end
if @option = 2
begin
update abc set description=@description,active=@active
where code = @code
if @@error <> 0
begin
raiserror( 'proc_abcInsUpdDel:ไม่สามารถบันทึกข้อมูลได้',16,-1)
end
end
if @option = 3
begin
delete from abc where code = @code
if @@error <> 0
begin
raiserror( 'proc_abcInsUpdDel:ไม่สามารถบันทึกข้อมูลได้',16,-1)
end
end

-- ทดสอบ insert
proc_abcInsUpdDel 1,'BB','TEST2',1

-- ทดสอบ insert โดยไม่มี active
proc_abcInsUpdDel 1,'CC','TEST3'

-- ทดสอบ update
proc_abcInsUpdDel 2,'CC','TEST4'

-- ทดสอบ delete
proc_abcInsUpdDel 3,'CCC'

-- ตรวจสอบข้อมูล
select * from abc;




Create Date : 22 มกราคม 2552
Last Update : 22 มกราคม 2552 6:51:54 น. 1 comments
Counter : 3770 Pageviews.

 
แวะมาทักทายค่ะ


โดย: sony23 วันที่: 22 มกราคม 2552 เวลา:7:08:08 น.  

ชื่อ : * blog นี้ comment ได้เฉพาะสมาชิก
Comment :
  *ส่วน comment ไม่สามารถใช้ javascript และ style sheet
 
 Pantip.com | PantipMarket.com | Pantown.com | © 2004 BlogGang.com allrights reserved.