存储过程返回bool

时间:2013-09-11 17:15:48

标签: sql-server tsql stored-procedures

我正在创建一个存储过程,用于检查用户正在保存的电子邮件(编辑个人资料电子邮件),以检查数据库中是否已存在针对其他用户的新电子邮件。如果输入的电子邮件在数据库中不存在则安全使用并保存,但如果它存在于数据库中且用户ID和名称与用户ID和保存人员的姓名不匹配意味着新电子邮件属于其他用户返回false,我将用于抛出和错误消息

这就是我所拥有的:

create procedure CheckDuplicate
@email nvarchar(256),
@Id int
As
Begin
set nocount on;
select usr.Id, usr.UserName, usr.Email
from Users usr
where usr.Email = @email and usr.Id = @Id
end

问题:如何添加bool以检查数据库中是否存在?

3 个答案:

答案 0 :(得分:2)

试试这个:

create procedure CheckDuplicate
@email nvarchar(256),
@Id int
As
Begin

set nocount on;

   Select Case When Exists (
      select usr.Id, usr.UserName, usr.Email
      from Users usr
      where usr.Email = @email and usr.Id = @Id
   )
   Then Cast(1 as bit)
   Else Cast(0 as bit) 
   End


End

答案 1 :(得分:2)

如果另一个用户拥有所请求的电子邮件地址,则返回1,否则返回0:

create procedure CheckDuplicate
  @email nvarchar(256),
  @Id int
As
  set nocount on;
  select case
    when exists ( select 42 from Users where Email = @email and Id <> @Id ) then Cast( 1 as Bit )
    else Cast( 0 as Bit ) end as EmailBelongsToAnotherUser

或者,您可以在输出参数中返回结果:

create procedure CheckDuplicate
  @email nvarchar(256),
  @Id int,
  @EmailCollision as Bit Output
As
  set nocount on;
  select @EmailCollision = case
    when exists ( select 42 from Users where Email = @email and Id <> @Id ) then Cast( 1 as Bit )
    else Cast( 0 as Bit ) end as EmailBelongsToAnotherUser

由于无需创建记录集来传递单个位,因此效率更高一些。

请注意,这应该在更新数据库的同一事务中完成。否则其他人可能会潜入,你会发生冲突。

答案 2 :(得分:0)

--IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')

create procedure CheckDuplicate
@email nvarchar(256),
@Id int
As
Begin
set nocount on;
IF EXISTS (select usr.Id, usr.UserName, usr.Email
from Users usr
where usr.Email = @email and usr.Id = @Id)
begin
Print 'YES' 
end
else
begin
Print 'NO' 
end

end