抑制 IGNORE_DUP_KEY 生成的 T-SQL 警告
有没有办法抑制通过在 IGNORE_DUP_KEY = ON 的索引上插入重复键而生成的警告?它给出的警告是“重复的密钥被忽略”。
出于性能原因,我正在研究将此选项与表变量一起使用,但它会生成大量警告消息。这可能是一个问题,因为我将脚本的输出记录到文本文件中,并且我不希望日志文件一遍又一遍地填满数百行此警告。
可以使用以下脚本重现这些警告。注意:这不是我的实际脚本,而只是用于说明目的的示例。
SET NOCOUNT ON;
SET ANSI_WARNINGS OFF;
DECLARE @data TABLE (x int NOT NULL PRIMARY KEY);
DECLARE @i int;
SET @i = 1;
WHILE @i <= 1000
BEGIN
INSERT INTO @data (x) VALUES (@i);
SET @i = @i + 1;
END;
DECLARE @test TABLE (x int NOT NULL PRIMARY KEY WITH (IGNORE_DUP_KEY = ON));
SET @i = 2;
WHILE @i <= 1000
BEGIN
INSERT INTO @test (x) SELECT x FROM @data WHERE (x % @i) = 0 AND x > @i
SET @i = (SELECT MIN(x) FROM @data d WHERE x > @i
AND NOT EXISTS (SELECT 1 FROM @test t WHERE t.x=d.x));
END;
SELECT COUNT(*) FROM @test;
这类似于 如何在运行 SQL Server 2005 脚本时抑制 T-SQL 警告?,但是那里的解决方案在这种情况下不起作用。我还看到了使用 TRY...CATCH 的建议,但这也不起作用:看来您无法捕获警告。
我正在使用 SQL Server 2005。
Is there a way to suppress warnings generated by inserting duplicate keys on indexes with IGNORE_DUP_KEY = ON? The warning it gives is "Duplicate key was ignored."
I am investigating using this option with a table variable for performance reasons, but it generates a lot of warning messages. This can be a problem since I log the output of my script to a text file, and I don't want the log file to fill up with hundreds of lines of this warning over and over.
The warnings can be reproduced with the following script. Note: this is not my actual script, but merely an example for illustration purposes.
SET NOCOUNT ON;
SET ANSI_WARNINGS OFF;
DECLARE @data TABLE (x int NOT NULL PRIMARY KEY);
DECLARE @i int;
SET @i = 1;
WHILE @i <= 1000
BEGIN
INSERT INTO @data (x) VALUES (@i);
SET @i = @i + 1;
END;
DECLARE @test TABLE (x int NOT NULL PRIMARY KEY WITH (IGNORE_DUP_KEY = ON));
SET @i = 2;
WHILE @i <= 1000
BEGIN
INSERT INTO @test (x) SELECT x FROM @data WHERE (x % @i) = 0 AND x > @i
SET @i = (SELECT MIN(x) FROM @data d WHERE x > @i
AND NOT EXISTS (SELECT 1 FROM @test t WHERE t.x=d.x));
END;
SELECT COUNT(*) FROM @test;
This is similar to How do I suppress T-SQL warnings when running a script SQL Server 2005?, but the solution there does not work in this case. I have also seen suggestions for using TRY...CATCH, but that does not work either: it appears you can't catch warnings.
I am using SQL Server 2005.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 SQL Server 2017 及更高版本中,有一个选项可以实现此目的:
In SQL Server 2017 and later, there is an option for this:
如果从表声明中删除“WITH (IGNORE_DUP_KEY = ON)”选项并使用 try/catch 块包装 INSERT 语句会怎样?请参阅下面的示例:
What if you removed the "WITH (IGNORE_DUP_KEY = ON)" option from the table declaration and instead wrapped your INSERT statement using a try/catch block. See the example below: