我有一个存储过程,可以将一些行插入表中。有时它似乎会失败(找不到新记录),尽管我知道语句确实执行了。我使用的代码如下。执行后,我可以在 tbl_DebugLog 表中找到相关行,但在 tbl_WebSiteNotifications 表中找不到。我使用的是 SQL Server 15.0.2。此外,该表是合并复制的一部分。什么会导致这种情况?
insert into tbl_WebSiteNotifications(NotificationType, FileID, UserID, SubscriptionID, InsertionDate)
select RequestType, FileID, UserID, SubscriptionID, DateRequested
from #TempNotifications
where UserID is not null
insert into tbl_DebugLog (LogDate, LogMessage, ServerName)
select getdate(), 'FileID ' + format(FileID,'D') + N' for SubscriptionID ' + format (SubscriptionID,'D') + N' Inserted into tbl_WebSiteNotifications' +
', NotificationType=' + format(RequestType,'D') +
', UserID=' + format(UserID,'D') +
', InsertionDate=' + format(DateRequested,'dd-MM-yyyy'),
@@SERVERNAME
from #TempNotifications
where UserID is not null
默认情况下,过程内的插入失败不会停止该过程。如果您希望它停止,请
XACT_ABORT
在过程开始时设置SET XACT_ABORT ON
,以便第一次插入将使过程失败。例如,此代码将到达 select
并且设置
XACT_ABORT ON
, 会使其在第二次插入时出现错误时停止。请参阅文档中的SET XACT_ABORT (Transact-SQL) 。
原因很可能是违反了某种约束。
为什么你看不到关于它的错误是一个更困难的问题。SP 不同部分的这两个语句是否被 包围
try ... catch
?是否有条件逻辑可以调用第二条语句而无需先运行?你如何运行这个存储过程?它是由某个客户端调用的吗?它是否隐藏了“不相关”的警告消息?
SET NOCOUNT ON
你的SP里有吗?删除它,然后从打印所有这些“垃圾”消息的客户端运行 SP - 它们在像您这样的情况下非常有帮助。如果您不喜欢选项中的消息,您可以在语句之间
nocount
添加很多内容。print "insert into tbl processed " + cast(@@rowcount as varchar(20))