在IF部分内创建程序

时间:2011-06-10 12:48:23

标签: sql-server tsql

我需要一些简单的SQL代码帮助:

DECLARE @procExists int
SET @procExists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = 'dbo' AND ROUTINE_NAME = 'Table_Exists' AND ROUTINE_TYPE = 'PROCEDURE')
IF NOT @procExists > 0 
BEGIN
    -- test query
    -- SELECT 'Something' = @procExists;

    -- error throwing code
    -- 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

上面的简单代码:
- 声明一个int变量
- 检查程序dbo.Table_Exists是否存在 - 如果不存在则创建它

我的问题是这个错误信息:

Msg 156, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'PROCEDURE'.
Msg 137, Level 15, State 2, Line 13
Must declare the scalar variable "@schemaName".

我不知道为什么,但是..
- 当我执行'CREATE PROCEDURE'身体单独时,它会工作 - 当我执行整个IF部分不包括'CREATE PROCEDURE'正文时,简单查询工作
- 当我执行整个IF部分包括'CREATE PROCEDURE'正文时,会抛出错误

我缺少什么?

4 个答案:

答案 0 :(得分:21)

CREATE PROCEDURE必须在其自己的批次中

因此,动态SQL是一种方式:

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

或DROP第一次

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

注意使用OBJECT_ID来查看proc是否存在。

答案 1 :(得分:15)

您可以使用SET NOEXEC ON执行此操作。这指示SQL Server在到达SET NOEXEC OFF之前忽略所有SQL代码。

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

答案 2 :(得分:3)

来自MSDN

  

CREATE PROCEDURE语句不能与单个批处理中的其他Transact-SQL语句组合使用。

因此,除非您通过动态查询实现它,否则您尝试做的事情是不可能的。

答案 3 :(得分:0)

if OBJECT_ID('PROC1') IS NULL  
   EXEC('CREATE PROCEDURE DBO.PROC1 AS SELECT 1')

GO

ALTER PROCEDURE DBO.PROC1(@PARAM1 INT, @PARAM2 INT)

AS

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