受限制的用户插入值多于连接表行

时间:2014-02-13 19:07:23

标签: sql-server

我想创建银行交易表我创建了两个表

表1)

create table depo (datedep varchar(25),DepNo int ,cheqty int,Amount int);

表2)

create table cheq (datedep varchar(25),DepNo int,cheqno int, Bank names varchar(20),Client varchar(10),Amount int);

表1 depo

insert into depo values('01-01-2014',1920420,4,3000)

表2 cheq

insert into cheq values('01-01-2014',1920420,420420,,'SCB BANK','EUF',500)
insert into cheq values('01-01-2014',1920420,52665801,'ABL BANK','SNR',500)
insert into cheq values('01-01-2014',1920420,88888805,'NIB BANK','POP',1000)
insert into cheq values('01-01-2014',1920420,63532515,'BRL BANK','DAL',1000)
select * from depo
select * from cheq

我通过存储过程在表1中插入值我限制用户不从depo表中的该存储单1920420中插入超过4个cheq

create proc cheqs (@datedep varchar(25),@DepNo int,@cheqno int ,@Client varchar(10),@Amount int)
as
begin
if exists (select cheqty from depo as D join cheq as C
on D.depno=c.depno
where D.cheqty>c.depNo and c.depno= 1920420`)

rollback
else if exists (select cheqty from depo as D join cheq as C
on D.depno=c.depno
where D.cheqty<=c.depNo and c.depno=1920420`)`
insert into cheq values(@datedep,@DepNo,@cheqno,@Client,@Amount);
end   

如果用户在表2中输入超过4 cheq而不是回滚

1 个答案:

答案 0 :(得分:0)

CREATE PROCEDURE cheqs 
@datedep varchar(25),
@DepNo int,
@cheqno int ,
@Client varchar(10),
@Amount int
AS
BEGIN
 SET NOCOUNT ON;

IF EXISTS (SELECT 1 
           FROM depo as D INNER JOIN cheq as C
           ON D.depno=c.depno
           WHERE D.cheqty > c.depNo 
           AND   c.depno  = 1920420)
    BEGIN
      RETURN
    END 
  ELSE 
   BEGIN
      INSERT INTO  cheq (datedep,DepNo,cheqno,Client,Amount)
      VALUES(@datedep,@DepNo,@cheqno,@Client,@Amount);
   END
END