如何检查SQL数据库中是否存在函数?
我需要查明数据库中是否存在某个函数,以便我可以删除它并再次创建它。它基本上应该类似于我用于存储过程的以下代码:
IF EXISTS (
SELECT *
FROM dbo.sysobjects
WHERE id = OBJECT_ID(N'[dbo].[SP_TEST]')
AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
I need to find out if a function exists in a database, so that I can drop it and create it again. It should basically be something like the following code that I use for stored procedures:
IF EXISTS (
SELECT *
FROM dbo.sysobjects
WHERE id = OBJECT_ID(N'[dbo].[SP_TEST]')
AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这就是 SSMS 在使用
DROP 和 CREATE
选项编写脚本时所使用的内容。这种部署更改的方法意味着您需要重新创建对象的所有权限,因此您可能会考虑
ALTER
- ing if Exists 代替。This is what SSMS uses when you script using the
DROP and CREATE
optionThis approach to deploying changes means that you need to recreate all permissions on the object so you might consider
ALTER
-ing if Exists instead.我倾向于将 Information_Schema:
用于函数,并更改
Routine_Type
用于存储过程I tend to use the Information_Schema:
for functions, and change
Routine_Type
for stored procedures为什么不只是:
object_id
的第二个参数是可选的,但可以帮助识别正确的对象。有 此类型参数有许多可能的值,特别是:Why not just:
The second argument of
object_id
is optional, but can help to identify the correct object. There are numerous possible values for this type argument, particularly:我知道这个线程很旧,但我只是想为那些认为
Alter
比Drop
和Create
更安全的人添加这个答案。下面的代码将更改
函数
(如果存在)或创建
(如果不存在):I know this thread is old but I just wanted to add this answer for those who believe it's safer to
Alter
thanDrop
andCreate
. The below willAlter
theFunction
if it exists orCreate
it if doesn't:我发现您可以使用一种非常不冗长且直接的方法来检查各种 SQL Server 对象是否存在:
这基于 SQL 2005+ 中提供的 OBJECTPROPERTY 函数。可以在此处找到该 MSDN 文章。
OBJECTPROPERTY 函数使用以下签名:
将文字值传递到属性参数中,指定要查找的对象的类型。您可以提供大量的值。
I've found you can use a very non verbose and straightforward approach to checking for the existence various SQL Server objects this way:
This is based on the OBJECTPROPERTY function which is available in SQL 2005+. The MSDN article can be found here.
The OBJECTPROPERTY function uses the following signature:
You pass a literal value into the property parameter, designating the type of object you are looking for. There's a massive list of values you can supply.
从 SQL Server 2016 SP1、SQL Server 2017 或更高版本中,您可以使用以下语法:
为了避免跳过这些环节。这还有一个关于持久化过程的元数据的额外好处(而不是每次更改它时都会获得一个全新的 objectid),这有时很有用,特别是当您使用 QueryStore 或其他关心 objectid 的工具时。
From SQL Server 2016 SP1, SQL Server 2017 or later, you can use the syntax:
To avoid jumping through these hoops. This has an additonal benefit of metadata about the procedure being persisted (rather than every time you change it it getting a brand new objectid) which can sometimes be useful, especially if you use things like QueryStore or other tools that care about the objectid.