如果条件不起作用

时间:2015-01-19 20:05:30

标签: sql

如果记录不在表格中,我想显示一条消息。

我写了一小段代码,但它给了我一个错误。

create procedure abc(@id varchar(25))
as
   declare @msg1 as varchar(55)
begin
   select id,fname,lname from student where id=@id
   --up to this is working correctly
   --for showing msg i write down this lince of code
   if id=@id
      select @msg=“correct record“
   else
      select @msg=“record not found“
   end
end

2 个答案:

答案 0 :(得分:3)

添加EXISTS检查而不是选择记录

IF EXISTS ( select 1 from student where id=@id)
BEGIN
   SET @msg = 'correct record'
END
ELSE
BEGIN 
   SET @msg = 'incorrect record'
END

您是否尝试返回@msg的值?如果是,请在结尾处添加SELECT @msg

答案 1 :(得分:1)

使用单引号不加倍。并使用@@ rowcount

检查任何结果
create procedure abc(@id varchar(25))
as
begin
   select id,fname,lname from student where id=@id

 if @@rowcount > 0
      select 'correct record' as msg
   else
      select 'record not found' as msg
   end
end