您可以使用information_schema中包含的系统视图来在表格中搜索、视图和(未加密)存储过程与一个脚本。我前段时间开发了这样一个脚本,因为我需要在数据库中到处搜索字段名称。
下面的脚本首先列出了包含您要搜索的列名的表/视图,然后是找到该列的存储过程源代码。它将结果显示在一个表中以区分 “BASE TABLE”、“VIEW”和“PROCEDURE”,并(可选)在第二个表中显示源代码:
DECLARE @SearchFor nvarchar(max)='%CustomerID%' -- search for this string
DECLARE @SearchSP bit = 1 -- 1=search in SPs as well
DECLARE @DisplaySPSource bit = 1 -- 1=display SP source code
-- tables
if (@SearchSP=1) begin
(
select '['+c.table_Schema+'].['+c.table_Name+'].['+c.column_name+']' [schema_object],
t.table_type
from information_schema.columns c
left join information_schema.Tables t on c.table_name=t.table_name
where column_name like @SearchFor
union
select '['+routine_Schema+'].['+routine_Name+']' [schema_object],
'PROCEDURE' as table_type from information_schema.routines
where routine_definition like @SearchFor
and routine_type='procedure'
)
order by table_type, schema_object
end else begin
select '['+c.table_Schema+'].['+c.table_Name+'].['+c.column_name+']' [schema_object],
t.table_type
from information_schema.columns c
left join information_schema.Tables t on c.table_name=t.table_name
where column_name like @SearchFor
order by c.table_Name, c.column_name
end
-- stored procedure (source listing)
if (@SearchSP=1) begin
if (@DisplaySPSource=1) begin
select '['+routine_Schema+'].['+routine_Name+']' [schema.sp], routine_definition
from information_schema.routines
where routine_definition like @SearchFor
and routine_type='procedure'
order by routine_name
end
end
如果您运行查询,请使用“result as text”选项 - 然后您可以使用“find”在结果集中查找搜索文本(对于长源代码很有用)。
注意,如果您只想显示 SP 名称,并且如果您只是在查找表/视图而不是 SP,您可以将 @DisplaySPSource 设置为 0可以将@SearchSP设置为0。
示例结果(在 Northwind 数据库中查找 CustomerID,结果通过 LinqPad 显示):
注意我已经用测试视图验证了这个脚本dbo.TestOrders
即使SELECT 语句中使用了c.*,它在此视图中也找到了CustomerID(引用表Customers 包含CustomerID,因此视图显示此列)。
注意 LinqPad用户:在C#中,你可以使用dc.ExecuteQueryDynamic(sqlQueryStr, new object[] {... parameters ...} ).Dump();,参数为@p0 ... @ 987654339@ 在查询字符串中。然后,您可以编写一个静态扩展类并将其保存在 My Extensions 下,以便在您的 LinqPad 查询中使用。数据上下文可以通过参数从查询窗口作为DataContextBase dc 传递,即公共静态扩展类中的public static void SearchDialog(this DataContextBase dc, string searchString = "%")(在LinqPad 6 中,它是DataContext)。然后您可以将上面的 SQL 查询重写为带有参数的字符串,并从 C# 上下文中调用它。