我正在对旧版数据库运行大型依赖项扫描,并发现某些对象具有过时的引用链接,如果您在SSMS for View中运行此代码以指向不存在的表(如我的情况),您将在{ {1}}标签和Results
中的错误信息。就像下面的情况一样。
我试图检查我所知道的所有env内容以及该存储过程的输出,但是没有看到任何指示。
在循环的动态SQL脚本中运行该事件时如何捕获该事件,并在表中捕获输出以进行进一步处理?
已更新:
Messages
框中输入文字,出现错误时,您仍然在Message
标签-
Results
-
答案 0 :(得分:1)
tldr是您无法在服务器端捕获这些消息,并且必须使用C#,PowerShell或其他可以处理信息消息的客户端程序中的客户端程序。
DMV正在做一些我不完全理解的奇怪事情。它会生成错误(不允许使用普通的UDF执行),并且这些错误不会触发TRY / CATCH块或设置@@ error。 EG
create table tempdb.dbo.foo(id int)
go
create view dbo.v_View_Obs_Table
as
select * from tempdb.dbo.foo
go
drop table tempdb.dbo.foo
go
begin try
Select * From sys.dm_sql_referenced_entities('dbo.v_View_Obs_Table','Object')
end try
begin catch
select ERROR_MESSAGE(); --<-- not hit
end catch
但是这些都是 real 错误,如您所见,可以从客户端代码运行此错误:
using System;
using System.Data.SqlClient;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
using (var con = new SqlConnection("Server=.;database=AdventureWorks;integrated security=true"))
{
con.Open();
con.FireInfoMessageEventOnUserErrors = true;
con.InfoMessage += (s, a) =>
{
Console.WriteLine($"{a.Message}");
foreach (SqlError e in a.Errors)
{
Console.WriteLine($"{e.Message} Number:{e.Number} Class:{e.Class} State:{e.State} at {e.Procedure}:{e.LineNumber}");
}
};
var cmd = con.CreateCommand();
cmd.CommandText = "Select * From sys.dm_sql_referenced_entities('dbo.v_View_Obs_Table','Object')";
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read() || (rdr.NextResult() && rdr.Read()))
{
Console.WriteLine(rdr[0]);
}
}
Console.ReadKey();
}
}
}
}
输出
Invalid object name 'tempdb.dbo.foo'.
Invalid object name 'tempdb.dbo.foo'. Number:208 Class:16 State:3 at v_View_Obs_Table:4
0
The dependencies reported for entity "dbo.v_View_Obs_Table" might not include references to all columns. This is either because the entity references an object that does not exist or because of an error in one or more statements in the entity. Before rerunning the query, ensure that there are no errors in the entity and that all objects referenced by the entity exist.
The dependencies reported for entity "dbo.v_View_Obs_Table" might not include references to all columns. This is either because the entity references an object that does not exist or because of an error in one or more statements in the entity. Before rerunning the query, ensure that there are no errors in the entity and that all objects referenced by the entity exist. Number:2020 Class:16 State:1 at :1