SQL服务器 - 在创建之前检查SP中是否存在对象

时间:2017-08-30 07:29:31

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

为什么关注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

1 个答案:

答案 0 :(得分:0)

您可以使用元数据表检查数据库中是否存在对象。对于存储过程和函数,您可以使用表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