title: Must declare the scalar variable "@varname" in database creation script
body: <p>I'm trying to create a script for basic database and login/user creation for SqlServer
  When i run my script I get many errors like:</p>
  
  <blockquote>
    <p>Must declare the scalar variable "@varname"</p>
  </blockquote>
  
  <p>when the variable is used in an <code>EXEC</code> statement for the second time during the script execution.</p>
  
  <pre><code>declare
       @dbname nvarchar(50) ,
       @userName nvarchar(50) ,
       @password nvarchar(50);
  SET @dbname = N'DBNAME';
  SET @userName = N'DBUSERNAME';
  SET @password= N'PASSWORD';
  
  Begin transaction
      IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = @dbname)
      BEGIN
          exec ('
              DROP login '+ @userName + '
              DROP USER '+  @userName + '
              alter database '+  @dbname + '
              SET OFFLINE 
              WITH ROLLBACK IMMEDIATE;
              ALTER DATABASE '+  @dbname + '
              SET ONLINE;
              DROP DATABASE '+  @dbname)
      END 
  
      SET ANSI_NULLS ON
      GO
      SET QUOTED_IDENTIFIER ON
      GO
      SET ANSI_PADDING ON
      GO
      EXEC ('CREATE DATABASE '+ @dbname)
      GO 
      EXEC (@dbname+ '.[dbo].[sp_fulltext_database] @action = ''disable''')
      GO 
      EXEC ('ALTER DATABASE '+ @dbname + ' SET COMPATIBILITY_LEVEL = 100')
      GO 
       ...
      EXEC ('ALTER DATABASE '+ @dbname + ' SET DB_CHAINING OFF')
      GO
  
      EXEC('create login '+ @userName + 'with password = '+ @password);
      EXEC('use  '+ @dbname+ '
      create user '+ @userName + ' for login '+ @userName);
      EXEC ('EXEC sp_addrolemember  ''db_owner'', '+  @userName)
  
  commit transaction
  </code></pre>
  
  <p>Have I to use <a href="http://msdn.microsoft.com/en-us/library/ms188001%28v=SQL.90%29.aspx" rel="nofollow">sp_executesql</a> for every query? Is there a shorter solution?</p>