存储过程中的IF条件

时间:2014-02-22 10:55:58

标签: sql sql-server stored-procedures

我有两张桌子:studentsece200_atten

  • 第一个表students有两列:id, ece200,但ece200bit =>真或假
  • 第二个表ece200_attend有一列id

当我插入id时,我想检查(如果此id = 1的ece200)在表ece200_attend中插入该id。

我的代码:

alter proc test
   @myid int    
as 
begin
   declare @mycourse bit = 1

   select @mycourse = ece200 from students 

   if @mycourse = 1
      insert into ece200_attend (id) values (@myid)
end
go

exec test 34003

2 个答案:

答案 0 :(得分:2)

if exists (select * from students where id = @myid and ece2000 = 1)
    begin
    insert into ece200_attend (id) values (@myid)
    end

答案 1 :(得分:1)

试试这个,

ALTER PROC test(@myid int)
AS BEGIN
IF EXISTS(SELECT 1 FROM STUDENTS WHERE ece200=1)
    INSERT INTO ece200_attend (id) values (@myid)
GO


EXEC TEST 34003