Creating procedure inside IF section

后端 未结 4 535
孤街浪徒
孤街浪徒 2021-01-04 17:54

I need some help with simple SQL code:

DECLARE @procExists int
SET @procExists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = \'d         


        
相关标签:
4条回答
  • 2021-01-04 18:29

    From MSDN:

    The CREATE PROCEDURE statement cannot be combined with other Transact-SQL statements in a single batch.

    Therefore, what you are trying to do is not possible, unless you are fine with implementing it via a dynamic query.

    0 讨论(0)
  • 2021-01-04 18:34

    CREATE PROCEDURE has to be in it's own batch

    So, dynamic SQL is one way:

    IF OBJECT_ID('Table_Exists') IS NULL
    BEGIN
        EXEC ('CREATE PROCEDURE Table_Exists
             @schemaName varchar(50),
             @tableName varchar(50)
         AS
             RETURN (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schemaName AND TABLE_NAME = @tableName)
    ')
    END
    

    or DROP first

    IF OBJECT_ID('Table_Exists') IS NOT NULL
      DROP PROC Table_Exists
    GO
    CREATE PROCEDURE Table_Exists
             @schemaName varchar(50),
             @tableName varchar(50)
         AS
             RETURN (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schemaName AND TABLE_NAME = @tableName)
    GO
    

    Note the use of OBJECT_ID to see if the proc exists.

    0 讨论(0)
  • 2021-01-04 18:38

    You can do this using SET NOEXEC ON. This instructs SQL Server to ignore all SQL code until SET NOEXEC OFF is reached.

    IF EXISTS (SELECT *
              FROM INFORMATION_SCHEMA.ROUTINES
              WHERE ROUTINE_TYPE = 'PROCEDURE'
              AND ROUTINE_SCHEMA = 'dbo'
              AND ROUTINE_NAME = 'HelloWorld')
    BEGIN
        SET NOEXEC ON
    END
    GO
    
    CREATE PROCEDURE dbo.HelloWorld
    AS
        PRINT 'Hello world'
    GO
    
    SET NOEXEC OFF
    GO
    
    0 讨论(0)
  • 2021-01-04 18:50
    if OBJECT_ID('PROC1') IS NULL  
       EXEC('CREATE PROCEDURE DBO.PROC1 AS SELECT 1')
    
    GO
    
    ALTER PROCEDURE DBO.PROC1(@PARAM1 INT, @PARAM2 INT)
    
    AS
    

    .................

    0 讨论(0)
提交回复
热议问题