SET附近的语法不正确。期待外在

时间:2014-11-11 16:23:56

标签: sql sql-server stored-procedures

我正在尝试检查存储过程是否存在,如果不存在,则创建它。

我收到了错误

  

SET附近的语法不正确。期待外部

代码:

IF (NOT EXISTS (SELECT * 
             FROM INFORMATION_SCHEMA.ROUTINES 
             WHERE ROUTINE_SCHEMA = 'dbo' 
             AND  ROUTINE_NAME = 'ELMAH_GetErrorXml'))
BEGIN
    CREATE PROCEDURE [dbo].[ELMAH_GetErrorXml]
    (
        @Application NVARCHAR(60),
        @ErrorId UNIQUEIDENTIFIER
    )
    AS

        SET NOCOUNT ON

        SELECT 
            [AllXml]
        FROM 
            [ELMAH_Error]
        WHERE
            [ErrorId] = @ErrorId
        AND
            [Application] = @Application
END

3 个答案:

答案 0 :(得分:8)

您遇到了这个错误,因为这不是检查对象(过程)是否存在的权利,如果不存在则创建它。试试这样的事情。

IF NOT EXISTS (SELECT *
               FROM   sys.objects
               WHERE  object_id = Object_id(N'[dbo].[ELMAH_GetErrorXml]')
                      AND type IN ( N'P', N'PC' ))
  BEGIN
      EXEC('CREATE PROCEDURE [dbo].[Elmah_geterrorxml] (@Application NVARCHAR(60),
                                                        @ErrorId     UNIQUEIDENTIFIER)
            AS
              BEGIN
                  SET NOCOUNT ON

                  SELECT [AllXml]
                  FROM   [ELMAH_Error]
                  WHERE  [ErrorId] = @ErrorId
                         AND [Application] = @Application
              END')
  END

但简单的方法是

IF EXISTS (SELECT *
           FROM   INFORMATION_SCHEMA.ROUTINES
           WHERE  ROUTINE_SCHEMA = 'dbo'
                  AND ROUTINE_NAME = 'ELMAH_GetErrorXml')
  BEGIN
      DROP PROCEDURE [dbo].[Elmah_geterrorxml]
  END

GO

CREATE PROCEDURE [dbo].[Elmah_geterrorxml] (@Application NVARCHAR(60),
                                            @ErrorId     UNIQUEIDENTIFIER)
AS
  BEGIN
      SET NOCOUNT ON

      SELECT [AllXml]
      FROM   [ELMAH_Error]
      WHERE  [ErrorId] = @ErrorId
             AND [Application] = @Application
  END 

答案 1 :(得分:0)

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF EXISTS (SELECT 1 FROM sys.objects where name = 'ELMAH_GetErrorXml' and type ='P')
Drop Procedure [dbo].[ELMAH_GetErrorXml]
Go

CREATE PROCEDURE [dbo].[ELMAH_GetErrorXml]
(
@Application NVARCHAR(60),
@ErrorId UNIQUEIDENTIFIER
)
AS

SET NOCOUNT ON

SELECT
    [AllXml]
FROM
    [ELMAH_Error]
WHERE
    [ErrorId] = @ErrorId
AND
    [Application] = @Application

END

GO
SET QUOTED_IDENTIFIER OFF
GO
 SET ANSI_NULLS ON
 GO

答案 2 :(得分:-1)

尝试以下操作:

创建或更改程序 usp_SomeProcedure 作为 选择 '程序创建'