简体   繁体   English

检查是否存在存储过程

[英]checking for existence of a stored procedure

Does any body know why the following SQL returns a syntax error (Incorrect syntax near 'IF') in SQL Server 2012? 是否有人知道为什么以下SQL在SQL Server 2012中返回语法错误(“ IF”附近的语法不正确)?

DROP PROCEDURE IF EXISTS MyStoredProcedure;

I know I can use the following instead: 我知道我可以改用以下内容:

IF EXISTS(SELECT 1 FROM sys.procedures 
      WHERE Name = 'MyStoredProcedure')

But I wonder why the first one produces the error. 但是我不知道为什么第一个会产生错误。

Thanks! 谢谢!

This works: 这有效:

IF EXISTS(SELECT 1 FROM sys.procedures 
      WHERE Name = 'MyStoredProcedure')
      print 'yes'
      -- drop procedure mystoredprocedure

You must have something else in your query window that's throwing the error, or you're running things in the wrong order. 您的查询窗口中必须有其他东西引发错误,或者您以错误的顺序运行事物。

For what it's worth, this is my "go to" for dropping/building procedures before I CREATE PROCEDURE ... all my saved proc scripts have this. 对于它的价值,这是我在CREATE PROCEDURE过程之前“删除” /构建过程的“开始”……所有保存的proc脚本都具有此功能。

IF OBJECT_ID('dbo.uspSomeProcName') IS NOT NULL
BEGIN
    DROP PROCEDURE dbo.uspSomeProcName
    IF OBJECT_ID('dbo.uspSomeProcName') IS NOT NULL
        PRINT '<<< FAILED DROPPING PROCEDURE dbo.uspSomeProcName>>>'
    ELSE
        PRINT '<<< DROPPED PROCEDURE dbo.uspSomeProcName>>>'
END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM