如何在另一个数据库中创建引用调用者中正确的 sys.objects 表的 UDF 或视图?
使用 SQL Server 2008,我想创建一个 UDF,为我提供对象的创建日期。这是代码:
create function dbo.GetObjCreateDate(@objName sysname) returns datetime as
begin
declare @result datetime
select @result = create_date from sys.objects where name = @objname
return @result
end
go
我想将此 UDF 放入主数据库或其他一些共享数据库中,以便可以从任何地方访问它,除非我这样做,然后 sys.objects
引用将被拉出来自 master
数据库,而不是我从中发起查询的数据库。我知道您可以执行此操作,因为 information_schema
视图位于 master
中,并且只需包装对 sys.objects 本地实例的调用,因此我希望有一种简单的方法可以做到我的 UDF 也是如此。
Using SQL Server 2008, I'd like to create a UDF that gives me the create date of an object. This is the code:
create function dbo.GetObjCreateDate(@objName sysname) returns datetime as
begin
declare @result datetime
select @result = create_date from sys.objects where name = @objname
return @result
end
go
I'd like to put this UDF in the master database or some other shared database so that it is accessible from anywhere, except that if I do that then the sys.objects
reference pulls from the master
database instead of the database that I'm initiating my query from. I know you can do this as the information_schema
views sit in master
and just wrap calls to local instances of sys.objects, so I'm hoping there's a simple way to do that with my UDF as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
Try this:
为什么不这样做呢?
CREATE、
ALTER
或DROP
语句。然后触发器将执行步骤 #1 中的存储过程。这允许视图自动更新。存储过程 DDL:
函数 DDL:
示例用法:
Why not do this instead?
sys.objects
from each database on the server.CREATE
,ALTER
orDROP
statement is executed for a database. The trigger would then execute the stored procedure in step #1. This allows the view to be automatically updated.Stored Procedure DDL:
Function DDL:
Sample Usage:
它必须是一个函数吗?如果您只是希望它可以随处访问,一个技巧是将您的代码放在 varchar 中并对其进行 sp_executesql :
Does it have to be a function? If you just want it accessible everywhere, a trick is to put your code in a varchar and sp_executesql it:
似乎有一个未记录的存储过程允许您创建自己的系统对象:
sp_ms_marksystemobject
您可以在 http://www.mssqltips.com/tip.asp?tip=1612
There seems to be an undocumented stored procedure that allows you to create your own system objects:
sp_ms_marksystemobject
You can read more on http://www.mssqltips.com/tip.asp?tip=1612
查看如何编写自己的系统函数。我相信它可能对你有帮助
Have a look at How to Write Your Own System Functions. I believe that it may help you