我尝试使用存储过程在数据库中插入数据但是根据某些条件。例如,如果数据已存在于数据库中,则不应执行存储过程。 我正在做以下代码但它每次返回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
答案 0 :(得分: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
答案 1 :(得分: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标识为info meassage或exception。有关更多信息
答案 2 :(得分: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