I use the database name in several places in my script, and I want to be able to quickly change it, so I’m looking for something like this:
DECLARE @DBNAME VARCHAR(50) SET @DBNAME = 'TEST' CREATE DATABASE @DBNAME GO ALTER DATABASE @DBNAME SET COMPATIBILITY_LEVEL = 90 GO ALTER DATABASE @DBNAME SET RECOVERY SIMPLE GO
But it doesn’t work. So what’s the correct way to write this code?
Put the entire script into a template string, with {SERVERNAME} placeholders. Then edit the string using:
and then run it with
It’s hard to believe that, in the course of three years, nobody noticed that my code doesn’t work!
You can’t
EXECmultiple batches.GOis a batch separator, not a T-SQL statement. It’s necessary to build three separate strings, and then toEXECeach one after substitution.I suppose one could do something ‘clever’ by breaking the single template string into multiple rows by splitting on
GO; I’ve done that in ADO.NET code.And where did I get the word ‘SERVERNAME’ from?
Here’s some code that I just tested (and which works):