Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

sql server - Incorrect Syntax: Create Procedure must be the only statement in the batch

This question has been asked before but it all involved using "go" which I am not in need of here, at least I believe so.

I am following this tut https://www.youtube.com/watch?v=-xMGwiV5A6o, near the 1:25 mark exactly. And his seems to execute while mine doesn't.

    Select * From Snacks

    Create Proc spGetSnackByID
    @Id int
    as

    Begin
    Select Id, Name, Location
    from Snacks where Id = @Id
    End

Here is the exact error, being highlighted with the "BEGIN" statement:

"Msg 111, Level 15, State 1, Procedure spGetSnackByID, Line 7 'CREATE/ALTER PROCEDURE' must be the first statement in a query batch."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to keep the script as it is (select followed by a create procedure), you can construct the creation of the stored procedure in a NVARCHAR and EXECUTE it using sp_executesql. This way the CREATE statement is the first statement. Like this:

Select * From Snacks

EXECUTE sp_executesql N'
  Create Proc spGetSnackByID
  @Id int
  as
  Begin
    Select Id, Name, Location
    from Snacks where Id = @Id
  End
';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...