-- 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;