为什么存储过程不会使用IF语句创建表

时间:2015-05-05 19:01:05

标签: sql sql-server if-statement stored-procedures

USE [WORKFILES]
GO
/****** Object:  StoredProcedure [dbo].[MLINT]    Script Date: 05/04/2015 16:49:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MLINT]

AS

IF OBJECT_ID('WORKFILES.dbo.MLINT05', 'U') IS NULL

BEGIN
        --CREATE CMPDTE TABLE
CREATE TABLE WORKFILES.dbo.MLINT05
(DTSTAMP DATETIME NOT NULL)
END

BEGIN
        --INSERT TIMESTAMP
INSERT INTO WORKFILES.dbo.MLINT05
SELECT (getdate())
END

BEGIN
SELECT CONVERT(varchar(20), DTSTAMP)
FROM [WORKFILES].[dbo].[MLINT05]
END

我添加了一个转到我的SP

USE [WORKFILES]
GO
/****** Object:  StoredProcedure [dbo].[MLINT]    Script Date: 05/04/2015 16:49:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MLINT]

AS

IF OBJECT_ID('WORKFILES.dbo.MLINT05') IS NULL
GO

BEGIN
        --CREATE CMPDTE TABLE
CREATE TABLE WORKFILES.dbo.MLINT05
(DTSTAMP DATETIME NOT NULL)
END

BEGIN
        --INSERT TIMESTAMP
INSERT INTO WORKFILES.dbo.MLINT05
SELECT (getdate())
END

BEGIN
SELECT CONVERT(varchar(20), DTSTAMP)
FROM [WORKFILES].[dbo].[MLINT05]
END

1 个答案:

答案 0 :(得分:1)

Management Studio客户端使用go关键字来分隔批次。您不能在存储过程中使用它。实际上,如果在SSMS中的存储过程定义中使用go,则go将标记过程的结束。

您的过程在SQL Server 2012中运行正常。当旧版本看到已存在的表create table时,可能会出错。如果是这样,您可以使用动态SQL解决这个问题:

IF OBJECT_ID('WORKFILES.dbo.MLINT05', 'U') IS NULL
    BEGIN
    EXEC (N'CREATE TABLE WORKFILES.dbo.MLINT05 (DTSTAMP DATETIME NOT NULL)')
    END