1

I'm attempting to run a script that adds a login to MSSQL it includes two GO commands, both of which yield the error: Msg 102 ... Incorrect syntax near 'GO'. The following example code runs on a database named MyDB

DECLARE @currentUsername varchar(30);
DECLARE @password varchar(10);
SET @currentUsername = 'thisisatest';
SET @password = 'mypassword13';

DECLARE @addUser varchar(1000);
SET @addUser = '
    CREATE LOGIN ' + @currentUsername + '
    WITH PASSWORD = ''' + @password + ''',
    DEFAULT_DATABASE = [MyDB]
    GO
    USE MyDB
    CREATE USER ' + @currentUsername + ' FOR LOGIN ' + @currentUsername + '
    EXEC sp_addrolemember ''db_datareader'', ''' + @currentUsername + '''
    EXEC sp_addrolemember ''db_datawriter'', ''' + @currentUsername + '''
    GO
';
PRINT @addUser;
EXEC (@addUser);
AaronF
  • 2,841
  • 3
  • 22
  • 32
  • It may not be the word go but something near it that has incorrect syntax. Could be related to embedded quotes. – dinomix Aug 26 '15 at 23:03
  • 3
    GO is batch terminator, not part of T-SQL. See http://stackoverflow.com/questions/32212077/the-proper-use-of-mssql-go-in-vba/32212122#32212122 – Lukasz Szozda Aug 26 '15 at 23:04
  • Thanks. I'm fairly new to MSSQL. I see the GO keyword all over the place in scripts. – AaronF Aug 26 '15 at 23:06
  • 1
    And second thing consider using `EXEC dbo.sp_executesql @sql, @param_list, @args...` instead of concatenating string. – Lukasz Szozda Aug 26 '15 at 23:06
  • 2
    http://stackoverflow.com/questions/2299249/what-is-the-use-of-go-in-sql-server-management-studio , http://stackoverflow.com/questions/24593100/go-command-causing-a-failure-in-a-call-to-exec-function – user2864740 Aug 26 '15 at 23:12

1 Answers1

3

GO isn't a regular SQL statement. From MSDN:

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.

Try breaking it up into multiple calls like this:

DECLARE @currentUsername varchar(30);
DECLARE @password varchar(10);
SET @currentUsername = 'thisisatest';
SET @password = 'mypassword13';

DECLARE @addUser varchar(1000);
SET @addUser = '
    CREATE LOGIN ' + @currentUsername + '
    WITH PASSWORD = ''' + @password + ''',
    DEFAULT_DATABASE = [MyDB]
';
PRINT @addUser;
EXEC (@addUser);

SET @addUser = '
    USE MyDB
    CREATE USER ' + @currentUsername + ' FOR LOGIN ' + @currentUsername + '
    EXEC sp_addrolemember ''db_datareader'', ''' + @currentUsername + '''
    EXEC sp_addrolemember ''db_datawriter'', ''' + @currentUsername + '''
';
PRINT @addUser;
EXEC (@addUser);
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331