1

Hi I'm tying to run an alter database statement and keep getting an error: (this is to go in a script which will run against a number of databases)

SELECT is_broker_enabled FROM sys.databases WHERE name = db_name()

DECLARE @SQL NVARCHAR(1024)


IF (SELECT is_broker_enabled FROM sys.databases WHERE name = db_name()) = 0
BEGIN

    SET @SQL = N'ALTER DATABASE [' + db_name() + '] SET SINGLE_USER WITH ROLLBACK IMMEDIATE';
    SELECT @SQL;
    sp_executesql @SQL;

    SET @SQL = N'ALTER DATABASE [' + db_name() + '] SET ENABLE_BROKER';
    SELECT @SQL;
    sp_executesql @SQL;


    SET @SQL = N'ALTER DATABASE [' + db_name() + '] SET MULTI_USER';
    SELECT @SQL;
    sp_executesql @SQL;

END 

SELECT is_broker_enabled FROM sys.databases WHERE name = db_name()

I keep getting

Msg 102, Level 15, State 1, Line 11 Incorrect syntax near 'sp_executesql'. Msg 102, Level 15, State 1, Line 15 Incorrect syntax near 'sp_executesql'. Msg 102, Level 15, State 1, Line 20 Incorrect syntax near 'sp_executesql'.

I'm doing something dumb - but like most syntax problems looking does not give rise to seeing...

3 Answers 3

3

Calling a stored procedure without EXEC is only allowed as the first line in a batch. Your calls are not.

Have you also considered this construct to do it in one go?

SET @SQL = N'
 ALTER DATABASE [' + db_name() + '] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
 ALTER DATABASE [' + db_name() + '] SET ENABLE_BROKER;
 ALTER DATABASE [' + db_name() + '] SET MULTI_USER;
';
SELECT @SQL;
EXEC sp_executesql @SQL;
Sign up to request clarification or add additional context in comments.

3 Comments

Not sure about your comment on the exec being the first line in the batch - i know its true for create - but even you do not have it as the first line... After a bit of testing - its the added EXEC that causing it to work. Dont worry, I'm feeling dumb by missing the exec!
@Ian P: What it means is you can leave out EXEC only for the first code line. Any other stored proc calls requires EXEC.
Didnt know that - but I suppose it has to be true otherwise highlighting a proc in SSMS and <f5> would not work. Still hopefully I wont forget the exec for another 5 years
2

Try with the exec keyword, like this:

exec sp_executesql @SQL;

That's the way how you call another stored procedure from inside a stored procedure (you could also use EXECUTE, which does exactly the same). Take care not to confuse it with the Exec(...) function (see also here).

Comments

1

Try this:

   EXECUTE sp_executesql @SQL;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.