Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Put the entire script into a template string, with {SERVERNAME} placeholders. Then edit the string using:</p> <pre><code>SET @SQL_SCRIPT = REPLACE(@TEMPLATE, '{SERVERNAME}', @DBNAME) </code></pre> <p>and then run it with </p> <pre><code>EXECUTE (@SQL_SCRIPT) </code></pre> <hr> <p>It's hard to believe that, in the course of three years, nobody noticed that my code <strong>doesn't work</strong>!</p> <p>You can't <code>EXEC</code> multiple batches. <code>GO</code> is a batch separator, not a T-SQL statement. It's necessary to build three separate strings, and then to <code>EXEC</code> each one after substitution. </p> <p>I suppose one could do something "clever" by breaking the single template string into multiple rows by splitting on <code>GO</code>; I've done that in ADO.NET code.</p> <p>And where did I get the word "SERVERNAME" from?</p> <p>Here's some code that I just tested (and which works):</p> <pre><code>DECLARE @DBNAME VARCHAR(255) SET @DBNAME = 'TestDB' DECLARE @CREATE_TEMPLATE VARCHAR(MAX) DECLARE @COMPAT_TEMPLATE VARCHAR(MAX) DECLARE @RECOVERY_TEMPLATE VARCHAR(MAX) SET @CREATE_TEMPLATE = 'CREATE DATABASE {DBNAME}' SET @COMPAT_TEMPLATE='ALTER DATABASE {DBNAME} SET COMPATIBILITY_LEVEL = 90' SET @RECOVERY_TEMPLATE='ALTER DATABASE {DBNAME} SET RECOVERY SIMPLE' DECLARE @SQL_SCRIPT VARCHAR(MAX) SET @SQL_SCRIPT = REPLACE(@CREATE_TEMPLATE, '{DBNAME}', @DBNAME) EXECUTE (@SQL_SCRIPT) SET @SQL_SCRIPT = REPLACE(@COMPAT_TEMPLATE, '{DBNAME}', @DBNAME) EXECUTE (@SQL_SCRIPT) SET @SQL_SCRIPT = REPLACE(@RECOVERY_TEMPLATE, '{DBNAME}', @DBNAME) EXECUTE (@SQL_SCRIPT) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload