I am trying to create a script that creates and populates tables, and then create the stored procedures for my app to access them. My script runs just fine until I get to the stored procedures. I’m trying to read a .sql file into my app and then run this script through my connection in one execution. Is there any way I can remove the ‘go’ keyword from this chunk of the script to make it run in one execution?
if object_id('GetStudentByID') is not null
drop procedure GetStudentByID;
go
create procedure GetStudentByID
(@StudentID INT)
as
select StudentID,FirstName,LastName
from Student
where StudentID = @StudentID;
Like This:
This is a common problem because, although it’s not immediately apparent, “GO” is not a SQL Server command. Rather it is a command implemented by Management Studio (and SQLCMD as well), to allow you to tell it how to divide up a stream of SQL command text into separate compilable batches.
As SQL Server itself has no such command, you have to go about it differently in cases where you need a SQL Script to fit within a stored procedure, Agent Job, etc. The SOP way to do this is via dyanmic SQL using either sp_executeCmd(…) or EXEC(‘string’) (as above).