Search code examples
sqlsql-servert-sqlsql-server-2014

Query to create stored procedure against a number of databases fails unexpectedly


I am trying to run a SQL query to create a stored procedure in several databases.

I am running the following query:

DECLARE @sqlStmt nvarchar(max)

select name from sys.databases where name not in ('master', 'tempdb', 'model', 'msdb')

DECLARE dbCursor CURSOR
FOR select name from sys.databases where name not in ('master', 'tempdb', 'model', 'msdb')

DECLARE @dbname varchar(max)

OPEN dbCursor

fetch next from dbCursor into @dbname

while @@FETCH_STATUS = 0
BEGIN
    declare @stmt nvarchar(max)
    SET @stmt = 'USE ' + @dbname + ';';
    EXECUTE sp_executesql @stmt

    declare @correctTableExists bit

    set @correctTableExists = (select case when Exists(SELECT TABLE_SCHEMA + '.' + TABLE_NAME, *
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME in ('MasterSchedules', 'Client'))
    THEN 1
    ELSE 0
    END)

if @correctTableExists = 1
    BEGIN TRY

        set @stmt = 'USE ' + @dbName + '

GO

CREATE PROCEDURE spGetMasterScheduleByID 
    @masterScheduleID int
AS 
BEGIN 
SELECT * FROM MasterSchedules 
WHERE MasterScheduleID = @masterScheduleID 
END'
        EXECUTE sp_executesql @stmt
    END TRY
    BEGIN CATCH
        SELECT   
            ERROR_NUMBER() AS ErrorNumber  
            ,ERROR_MESSAGE() AS ErrorMessage;
        print @stmt + '
        Failed for ' + @dbName
    END CATCH

FETCH NEXT FROM dbCursor
INTO @dbname
END
CLOSE dbCursor;
DEALLOCATE dbCursor;

However, I get the following error message:

Error 102
Incorrect syntax near 'GO'.

When I look at the Messages, I see the following message for every database name I'm running this against:

(1 row(s) affected)
USE [Database Name]

GO

CREATE PROCEDURE spGetMasterScheduleByID 
    @masterScheduleID int
AS 
BEGIN 
    SELECT * FROM MasterSchedules 
    WHERE MasterScheduleID = @masterScheduleID 
END
            Failed for [Database Name]

Why does SQL Server think that this is "incorrect syntax" given that it's clearly perfectly valid syntax? When I copy and paste that exact query into SSMS the query works perfectly.

I already tried running the query in several ways, such as

exec @stmt
execute @stmt
execute (@stmt)
EXECUTE sp_executesql @stmt

Solution

  • GO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor.

    https://msdn.microsoft.com/en-us/library/ms188037.aspx