[英]How to solve this error “ERROR 102 sql state 420000” which comes up when I try to create this procedure
I am trying to create a procedure which check whether the number entered (as a nvarchar type) already exists or not. 我试图创建一个过程来检查输入的数字(作为nvarchar类型)是否已经存在。 If it exists then the updation takes place, else an error is thrown out to the user.
如果存在,则会进行更新,否则会向用户抛出错误。 But am not able to create the procedure because as soon as I execute the command ERROR 102/156 SQL STATE 42000 comes up.
但是无法创建该过程,因为一旦执行命令ERROR 102/156 SQL STATE 42000,就会出现该过程。
CREATE PROCEDURE UpdateAWBUnique
(
@AWB as nvarchar,
@Internal as nvarchar
)
AS
BEGIN
SET NOCOUNT ON
if((SELECT count(*) From Def_tab WHERE AWB=@AWB) == 0)
BEGIN
UPDATE Def_tab SET AWB= @AWB
where Internal=@Internal
END
ELSE
BEGIN
PRINT 'Already Exits'
END
END
GO
FYI I use Microsoft SQL Server. 仅供参考,我使用Microsoft SQL Server。 How to clear this error and create the procedure?
如何清除此错误并创建程序?
Conditionally UPDATE and see if any changes happened 有条件地更新并查看是否发生任何更改
UPDATE Def_tab
SET AWB = @AWB
WHERE Internal = @Internal
AND NOT EXISTS (SELECT 1 FROM Def_tab t WHERE t.AWB= @AWB)
IF (@@ROWCOUNT = 0)
PRINT 'Already Exits'
Otherwise in a concurrent environment something may happen between 否则,在并发环境中,可能会在
if((SELECT count(*) From Def_tab WHERE AWB=@AWB) == 0)
and 和
BEGIN
UPDATE Def_tab SET AWB= @AWB
renderring the if
check useless 使
if
检查无效
You seem to want Def_Tab.AWB
to be unique. 您似乎希望
Def_Tab.AWB
是唯一的。 If so, you should let the database enforce the data integrity. 如果是这样,则应让数据库强制执行数据完整性。 Define a unique constraint:
定义唯一约束:
alter table t add constraint unq_def_tab_awb
unique (awb);
No stored procedure is needed. 不需要存储过程。
This will also check the value on insert
. 这还将检查
insert
上的值。 And because the database is doing the check, you don't have to worry about whether or not the stored procedure is actually called when someone updates the table. 并且由于数据库正在执行检查,因此您不必担心有人更新表时是否实际调用了存储过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.