我有一个SQL脚本,每次客户端执行“数据库管理”功能时都必须运行。该脚本包括在客户端数据库上创建存储过程。其中一些客户端在运行脚本时可能已经拥有存储过程,而另一些客户端可能没有。我需要将丢失的存储过程添加到客户端数据库中,但无论我如何尝试改变T-SQL语法,我都得到了这个结果

CREATE/ALTER PROCEDURE'必须是查询批处理中的第一个语句

我在创作作品之前读到过这种说法,但我不喜欢这样做。

IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'MyProc')
DROP PROCEDURE MyProc
GO

CREATE PROCEDURE MyProc
...

如何添加检查存储过程是否存在,如果存储过程不存在则创建它,如果存储过程存在则修改它?


当前回答

创建程序(如果不存在)结束

其他回答

在T-Sql中删除并重新创建存储的proc的最简单方法是**

Use DatabaseName
go
If Object_Id('schema.storedprocname') is not null
begin
   drop procedure schema.storedprocname
end
go

create procedure schema.storedprocname
as

begin
end

你为什么不简单点

    IF EXISTS(SELECT * FROM sys.procedures WHERE NAME LIKE 'uspBlackListGetAll')
    BEGIN
         DROP PROCEDURE uspBlackListGetAll
    END
    GO

    CREATE Procedure uspBlackListGetAll

..........

创建程序(如果不存在)结束

我也犯了同样的错误。我知道这个线程已经死了,但我想设置另一个选项除了“匿名过程”。

我是这样解决的:

Check if the stored procedure exist: IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='my_procedure') BEGIN print 'exists' -- or watever you want END ELSE BEGIN print 'doesn''texists' -- or watever you want END However the "CREATE/ALTER PROCEDURE' must be the first statement in a query batch" is still there. I solved it like this: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE -- view procedure function or anything you want ... I end up with this code: IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('my_procedure')) BEGIN DROP PROCEDURE my_procedure END SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].my_procedure ...

我知道这是一个非常老的帖子,但由于这出现在顶部搜索结果中,因此为那些使用SQL Server 2016 SP1 -的人添加了最新更新

create or alter procedure procTest
as
begin
 print (1)
end;
go

如果存储过程不存在,则创建存储过程;如果存储过程存在,则更改存储过程。

参考