我想创建一个存储过程来将数据插入数据库中的表中,但它应该是唯一的,所以我首先检查传入的参数:
create procedure SP_Insert
@name varchar(50)
AS
if not exists (select Name from Employees where Name = @name)
begin
insert into Employess (Name)
values (@name)
end
我的问题是,如何在执行存储过程后在代码中判断传递参数是否未被接受为唯一值?
在我的表单中我有一个按钮(Insert)和一个文本框(名称),当用户单击插入文本值传递给存储过程时,我想弹出一个消息框警告用户重复输入< / p>
答案 0 :(得分:1)
使用@@ ROWCOUNT确定行受影响并将值作为参数返回。请参阅此答案:How can I get the number of records affected by a stored procedure?
答案 1 :(得分:1)
你可以这样做:
insert into Employess (Name)
select @name
where not exists (select * from Employees where Name = @name)
select @@rowcount
现在@@rowcount
(返回给调用者)是零或一,取决于是否有插入。
var recordsUpdated = command.ExecuteScalar();
实际上你可以跳过select @@rowocount
而不是明确地返回任何内容。
var recordsUpdated = command.ExecuteNonQuery();
返回受影响记录的数量。我更喜欢更明确。有人可能会落后并改变程序,以便它做出改变@@rowcount
的其他事情。 (为什么?但他们可以。)他们可能不知道下游的某些东西取决于受影响的记录数。但如果它是明确的,无论是选定的值还是输出参数,那么有人可以告诉其他东西取决于该值。
答案 2 :(得分:0)
create procedure SP_Insert
@name varchar(50), @result bit output
AS
if not exists (select Name from Employees where Name=@name)
begin
insert into Employess (Name) Values (@name)
set @result = 1
End
else set @result = 0
答案 3 :(得分:0)
存储过程可以返回一个值。 您可以将SP更改为以下内容:
create procedure SP_Insert
@name varchar(50)
AS
BEGIN
if not exists (select Name from Employees where Name=@name)
begin
insert into Employees (Name) Values (@name)
Return 0
end
else begin
Return 1
end
END
以下是MSDN文章的链接,其中包含更多详细信息和示例: [https://msdn.microsoft.com/en-us/library/ms188655.aspx]