在存储过程中执行多个语句

时间:2018-12-04 09:02:04

标签: sql sql-server stored-procedures

我试图在一个存储过程中执行多个语句。基本上,这是一种无服务器架构,在该架构中,我无法生成SQL脚本,也无法运行这些脚本来生成SP或表。我唯一的方法是通过SP或Functions运行脚本。有什么线索可以通过编程方式执行批量语句。我尝试使用以下SP:

SET ANSI_NULLS ON   
SET QUOTED_IDENTIFIER ON

Alter PROCEDURE [dbo].[GenerateScript]   

AS
BEGIN

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Bar1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Bar1] 
AS
BEGIN
Select Foo from Table 
END
' 
END

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Bar2]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Bar2] 
AS
BEGIN
Select Foo from Table 
END
' 
END

END

这将产生以下错误:

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

1 个答案:

答案 0 :(得分:2)

问题不是您的sp_executesql命令,而是SQL的开始(错误实际上是在告诉您问题)。该错误告诉您CREATE / ALTER PROCEDURE'必须是查询批处理中的第一条语句,但是,批处理中具有的第一条命令是SET ANSI_NULLS ON

GOSET命令之间添加ALTER,以开始新的批处理(在SSMS / sqlcmd中):

SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

GO
ALTER PROCEDURE [dbo].[GenerateScript] ...