如果object_id不为null则创建/更改过程然后删除?

时间:2012-06-05 13:58:09

标签: sql sql-server sql-server-2008 stored-procedures

如果临时表已经存在,我希望程序首先检查。如果是,则删除表格并继续选择进入表格。但我得到了这个错误:

'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.

我的代码如下所示:

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetData]
    @Param_Id int
AS
BEGIN

If OBJECT_ID('temp_table') is not null
drop table temp_table

select data_info into temp_table
from data_info_table1

END

但我继续犯同样的错误。有什么建议吗?

7 个答案:

答案 0 :(得分:0)

你想让程序变成无效吗?尝试在程序内部设置Set Ansi Null On。

此外,如果您手动执行此操作,则可以先选择该代码并运行该代码,然后仅选择存储过程并单独运行它来更改选项。

答案 1 :(得分:0)

当脚本如下所示时,我收到相同的错误消息。这意味着缺少GO语句。

if Exists(select object_id from sys.objects where name = 'GetData' and type = 'p')
Begin
    Drop Proc GetData
End
GO --Missing part
CREATE PROCEDURE [dbo].[GetData]
@Param_Id int
AS
BEGIN
    If OBJECT_ID('temp_table') is not null
       drop table temp_table

    select data_info into temp_table from data_info_table1
END

答案 2 :(得分:0)

GO命令指示一批T-SQL语句的结束。 GO命令之后的任何语句都表示新批次查询或T-SQL语句的开始。因此,我建议您在开头删除GO命令并保留CREATE语句之前的命令,因此现在成为后续查询批处理中的第一个语句。

声明如下所示

SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

GO
CREATE PROCEDURE [dbo].[GetData] @Param_Id int
AS
BEGIN

If OBJECT_ID('temp_table') IS NOT NULL DROP table temp_table

SELECT data_info INTO temp_table FROM data_info_table1

END
GO

答案 3 :(得分:0)

您不希望创建2个不同用户丢失数据的可能性,因为您在数据库中使用永久结构,对吗?如果您创建静态表将会发生什么。然后它实际上非常简单。如果您使用会话临时表(名称看起来像#temp_table),您需要在tempdb数据库中查找这些内容:

IF OBJECT_ID('tempdb..#temp_table') IS NOT NULL

这只是一种预防措施,因为以#开头的名称表在查询完成时被删除,而这些表是特定于查询的,这意味着它不会干扰其他用户或请求的并行连接。你的整个脚本应该是这样的:

GO
If OBJECT_ID('GetData') is not null
      drop PROCEDURE GetData
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetData]
    @Param_Id int
AS
BEGIN

   If OBJECT_ID('tempdb..#temp_table') is not null
        drop table #temp_table

   select data_info into #temp_table
   from data_info_table1

    -- do what ever you need to do here with you data and spit it out to user.
END
GO

答案 4 :(得分:0)

尝试在DROP TABLE之后放置GO。我发现 IF OBJECT_ID()IS NOT NULL DROP TABLE ** 并不总是独立工作,但在GO之后它似乎是可靠的: IF OBJECT_ID()IS NOT NULL DROP TABLE ** GO

答案 5 :(得分:0)

存在编译器错误。 如果你真的想创建这个过程,如果表temp_table真的是tamp表,你可以尝试在创建过程之前删除它。 像这样:

If OBJECT_ID('temp_table') is not null
drop table temp_table
go

create PROCEDURE [dbo].[GetData]
    @Param_Id int
AS
BEGIN

If OBJECT_ID('temp_table') is not null
drop table temp_table

select data_info into temp_table
from data_info_table1

END

或者真正使用像#table,## table或@table

这样的临时表

答案 6 :(得分:-1)

如果您使用此更改存储过程怎么办?:

CREATE PROCEDURE [dbo].[GetData]
    @Param_Id int
AS
BEGIN

If EXISTS(SELECT * FROM sys.tables WHERE name = 'temp_table')
BEGIN
    drop table temp_table
END

DECLARE @SQL VARCHAR(1000)
SET @SQL = '
select data_info into temp_table
from data_info_table1'

EXEC(@SQL)

END