以下查询列出了数据库中的所有存储过程及其定义。它返回12行:
USE [HQ-211-STOCK-DBO]
SELECT OBJECT_NAME (object_id) AS sp_name,
[definition] AS sp_definition
FROM [HQ-211-STOCK-DBO].sys.sql_modules as st
WHERE OBJECTPROPERTY (object_id, 'IsProcedure') = 1
当我更改查询的第一行以使用其他数据库时:
USE [HQ-193-STOCK-DBO]
SELECT OBJECT_NAME (object_id) AS sp_name,
[definition] AS sp_definition
FROM [HQ-211-STOCK-DBO].sys.sql_modules as st
WHERE OBJECTPROPERTY (object_id, 'IsProcedure') = 1
返回零行。
当我现在更改查询的第4行(FROM行)时:
USE [HQ-193-STOCK-DBO]
SELECT OBJECT_NAME (object_id) AS sp_name,
[definition] AS sp_definition
FROM [HQ-193-STOCK-DBO].sys.sql_modules as st
WHERE OBJECTPROPERTY (object_id, 'IsProcedure') = 1
我退回了一行。
似乎前缀sys.sql_modules
的数据库名称不能正常工作。
有人可以指出我做错了什么吗?为什么我在引用sys.sql_modules
?
答案 0 :(得分:4)
OBJECT_NAME()
和OBJECTPROPERTY()
查看当前数据库。停止使用它们。通常你不会得到匹配(这会使你的WHERE
子句在第二个查询中返回0行 - 你可以通过返回object_id
然后检查当前数据库的sys.objects
来确认这些值),但有时你可能会得到错误的匹配,如果你碰巧对两个数据库中的对象都有object_id
。
(They also ignore isolation semantics, so can be completely blocked by other queries, even if you are using READ UNCOMMITTED / NOLOCK
。所以即使在相同的数据库中,我强烈建议使用连接到其他目录视图而不是辅助元数据函数。通常它不是问题,但它们'我保证会在最不合时宜的时候被封锁。)
相反,你可以说:
SELECT o.name AS sp_name, st.[definition] AS sp_definition
FROM [HQ-211-STOCK-DBO].sys.sql_modules as st
INNER JOIN [HQ-211-STOCK-DBO].sys.objects AS o
ON st.[object_id] = o.[object_id]
WHERE o.type = 'P';