我发现此代码将找到引用单个特定列的任何存储过程。现在我想创建一个查找引用多个特定列的存储过程的文件。
SELECT DISTINCT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%tbl_name%'
AND OBJECT_DEFINITION(OBJECT_ID) LIKE '%CreatedDate%';
如果可能,我有时可以指定列可能来自哪个表(有时是多个表)?
答案 0 :(得分:1)
当然,只需扩展您的SQL以包含其他AND子句,如:
SELECT DISTINCT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%tbl_name%'
AND OBJECT_DEFINITION(OBJECT_ID) LIKE '%CreatedDate%'
AND OBJECT_DEFINITION(OBJECT_ID) LIKE '%Other_tbl_name%'
AND OBJECT_DEFINITION(OBJECT_ID) LIKE '%Other_CreatedDate%';
这会对你有用吗?
另外,除非你的列名是每个表唯一的,否则你可能会得到误报,所以例如tbl_name可能被引用为CreatedDate列,但这并不意味着对CreatedDate的列引用来自tbl_name.CreatedDate。
此外,我不认为这会捕获动态SQL中的任何引用,因为只有文本的引用,并且不能绑定到系统对象。
答案 1 :(得分:0)
这应该可以解决问题:
CREATE TABLE dbo.TableA ( RowID INT, Name VARCHAR(20), StartDate DATETIME, EndDate DATETIME )
GO
CREATE TABLE dbo.TableB ( RowID INT, Name VARCHAR(20), StartDate DATETIME, EndDate DATETIME )
GO
CREATE VIEW dbo.ViewA AS SELECT RowID, StartDate, EndDate FROM dbo.TableA;
GO
CREATE VIEW dbo.ViewB AS SELECT RowID, StartDate, EndDate FROM dbo.TableB;
GO
CREATE PROC dbo.ProcA AS
SELECT RowID, Name, StartDate FROM dbo.TableA
RETURN
GO
CREATE PROC dbo.ProcB AS
SELECT RowID, Name, StartDate FROM dbo.TableB
RETURN
GO
SELECT o1.type_desc AS ReferencingObjectType
,OBJECT_SCHEMA_NAME(d.[object_id]) AS ReferencingSchema
,OBJECT_NAME(d.[object_id]) AS ReferencingObject
,COALESCE(COL_NAME(d.[object_id], d.column_id), '(n/a)') AS ReferencingColumn
,o2.type_desc AS ReferencedObjectType
,OBJECT_SCHEMA_NAME(d.referenced_major_id) AS ReferencedSchema
,OBJECT_NAME(d.referenced_major_id) AS ReferencedObject
,COALESCE(COL_NAME(d.referenced_major_id, d.referenced_minor_id), '(n/a)') AS ReferencedColumn
,d.class_desc
,d.is_selected
,d.is_updated
,d.is_select_all
FROM sys.sql_dependencies d
INNER JOIN sys.objects o1 ON o1.[object_id] = d.[object_id]
INNER JOIN sys.objects o2 ON o2.[object_id] = d.referenced_major_id
WHERE OBJECT_SCHEMA_NAME(referenced_major_id) = 'dbo'
AND OBJECT_NAME(referenced_major_id) = 'TableA'
AND COALESCE(COL_NAME(referenced_major_id, referenced_minor_id), '(n/a)') = 'StartDate'
见这里:https://msdn.microsoft.com/en-us/library/ms174402.aspx
请注意,sys.sql_dependencies将从SQL Server的未来版本中删除。我尝试使用推荐的目录视图(sys.sql_expression_dependencies)编写等效查询,但这似乎并没有提供所有table.column依赖项。
答案 2 :(得分:0)
您需要使用OR
运算符代替AND
SELECT name
FROM sys.procedures
WHERE Object_definition(object_id) LIKE '%Table1%'
OR Object_definition(object_id) LIKE '%Table2%'
OR Object_definition(object_id) LIKE '%Table3%'
OR Object_definition(object_id) LIKE '%Table4%'