【问题标题】:SQL server - Check for object existence in SP before creationSQL server - 在创建之前检查 SP 中的对象是否存在
【发布时间】:2017-08-30 07:29:30
【问题描述】:

为什么在创建或更改时跟随 SP 不会产生错误? 我在以下 SP 中使用了一个标量函数 [dbo.fn_General_GetCurrentTime()],它在数据库“AdventureWorks2014”中不存在。

我很困惑它是否应该给出错误。 有什么办法可以强制它检查对象是否存在?

USE [AdventureWorks2014]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[SP_Zee_Test]
    @ID   int
AS
BEGIN
    Declare @DateC DateTime

    Set @DateC = dbo.fn_General_GetCurrentTime() --this function is not exists in database
END

GO

【问题讨论】:

  • 人们几十年来一直在寻求某种方法来禁用延迟名称解析,但没有任何迹象表明很快就会实施任何事情。这是一个“功能”。

标签: sql-server stored-procedures sql-server-2014 user-defined-functions


【解决方案1】:

您可以使用元数据表检查数据库中是否存在对象。对于存储过程和函数,您可以使用表 INFORMATION_SCHEMA.ROUTINES

--check if a stored procedure exists
if exists (SELECT 1 from INFORMATION_SCHEMA.ROUTINES where ROUTINE_TYPE ='PROCEDURE' and ROUTINE_SCHEMA='yourSpSchema' and ROUTINE_NAME='yourSpName')
    begin
        --the stored procedure exists 
    end
else 
    begin
        --the stored procedure does not exist
    end

--check if a function exists
if exists (SELECT 1 from INFORMATION_SCHEMA.ROUTINES where ROUTINE_TYPE ='FUNCTION' and ROUTINE_SCHEMA='yourFxSchema' and ROUTINE_NAME='yourFxName')
    begin
        --the function exists 
    end
else 
    begin
        --the function does not exist
    end

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    相关资源
    最近更新 更多