0

我尝试使用存储过程在数据库中插入数据,但根据某些条件。例如,如果数据库中已经存在数据,则不应执行存储过程。我正在执行以下代码,但它每次都返回 0 而不是我想要的。我能做些什么

ALTER PROCEDURE dbo.SaveUser
(
  @cid int,
  @firstname varchar(20),
  @lastname varchar(20),
  @dob datetime,
  @gender varchar(20),
  @add varchar(100),
  @email varchar(40),
  @quali varchar(20), 
  @yop varchar(15), 
  @exp varchar(10),
  @pass varchar(20)

)
AS

declare @result int

if  EXISTS( select Email_ID from Registration where Email_ID=@email )
begin
    set @result=4;
    return @result;
end

else
begin
    insert into Registration values(@cid, @firstname, @lastname, @dob, @gender, @add, @email, @quali, @yop, @exp, @pass );
    set @result =0;
    return @result;
 end
4

3 回答 3

1

您可以在这种情况下使用 raiseerror 事件

if  EXISTS( select Email_ID from Registration where Email_ID=@email )
begin
    RAISERROR(N'Email id already exist.', 10, 2,'')
end

这里 10 是严重级别,根据严重级别 sql server 标识为信息消息或异常。了解更多信息

引发错误

数据库引擎严重级别

于 2013-09-25T06:14:27.383 回答
1

您可以简单地进行如下操作;

ALTER PROCEDURE dbo.SaveUser
(
  @cid int,
  @firstname varchar(20),
  @lastname varchar(20),
  @dob datetime,
  @gender varchar(20),
  @add varchar(100),
  @email varchar(40),
  @quali varchar(20), 
  @yop varchar(15), 
  @exp varchar(10),
  @pass varchar(20)    
)
AS
BEGIN

DECLARE @return int

if NOT EXISTS(select Email_ID from Registration where Email_ID=@email) 

insert into Registration values(@cid, @firstname, @lastname, 
                                @dob, @gender, @add, @email, 
                                @quali, @yop, @exp, @pass )
If (@@ERROR <> 0)
Begin
  Set @return = 4
Else
  Set @return = 0
End

Return @return

END
于 2013-09-25T05:58:25.913 回答
0

试试这个——

ALTER PROCEDURE dbo.SaveUser 
(
    @cid INT,
    @firstname VARCHAR(20),
    @lastname VARCHAR(20),
    @dob DATETIME,
    @gender VARCHAR(20),
    @add VARCHAR(100),
    @email VARCHAR(40),
    @quali VARCHAR(20),
    @yop VARCHAR(15),
    @exp VARCHAR(10),
    @pass VARCHAR(20)
)
AS BEGIN

    IF NOT EXISTS(
        SELECT 1 
        FROM dbo.Registration 
        WHERE Email_ID = @email
    ) BEGIN

        INSERT INTO dbo.Registration
        SELECT @cid, @firstname, @lastname, @dob, @gender, @add, @email, @quali, @yop, @exp, @pass

        RETURN 0;

    END

    RETURN 4;

END
于 2013-09-25T06:11:19.913 回答