Ending a stored procedure in .sql file

落爺英雄遲暮 提交于 2021-02-11 08:53:35

问题


I have this in an SQL file and I assumed that end is going to end the stored procedure:

create procedure Test4
as
begin
  select * from People
end
select * from Region

But instead, I got "Command completed successfully" and when I looked at the stored definition, I got:

ALTER procedure [dbo].[Test4]
as
begin
  select * from People
end
select * from Region

So what's the use of BEGIN/END in a stored procedure in SQL Server if it isn't to actually END it?


回答1:


According to the MSDN post on CREATE PROCEDURE, the BEGIN-END block is optional:

{ [ BEGIN ] sql_statement [;] [ ...n ] [ END ] } One or more Transact-SQL statements comprising the body of the procedure. You can use the optional BEGIN and END keywords to enclose the statements. For information, see the Best Practices, General Remarks, and Limitations and Restrictions sections that follow.

I just ran a test against MS SQL Server and noticed that if I include a query before the GO keyword after the END it gets included in the procedure:

CREATE PROCEDURE [dbo].[Test]

AS
BEGIN
    SELECT TOP 100 * FROM Test1
END
-- This gets included in the procedure
SELECT TOP 100 * FROM Test2
GO

Whereas if I type it after the GO, the query is left out of the procedure:

CREATE PROCEDURE [dbo].[Test]

AS
BEGIN
    SELECT TOP 100 * FROM Test1
END
GO
-- This gets chopped off when I open the procedure for editing later
SELECT TOP 100 * FROM Test2


来源:https://stackoverflow.com/questions/36943768/ending-a-stored-procedure-in-sql-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!