title: SQL create database if not exists, unexpected behaviour
body: <p>I have a long stored procedure which begins with the following statement:</p>
  
  <pre><code>IF  NOT EXISTS (SELECT * FROM sys.databases WHERE name = N'DBNAME')
      BEGIN
          CREATE DATABASE [DBNAME]
      END;
  </code></pre>
  
  <p>It is expected to create the DB on my local server, if it does not exist. The problem is that almost all of the time it goes thorugh this part of the stored procedure and does not create it, which then interferes with the other code from the same procedure. On the other hand, in very rare cases, it creates the DB. My question is: Is there a better way to check if the DB exists, because I have already tried at least 10.</p>
  
  <p>Other ways I tried:</p>
  
  <pre><code>IF  NOT EXISTS (SELECT 1 FROM sys.databases WHERE name = N'DBNAME')
      BEGIN
          CREATE DATABASE [DBNAME]
      END;
  
  IF  NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'DBNAME')
          BEGIN
              CREATE DATABASE [DBNAME]
          END;
  
  IF  NOT EXISTS (SELECT name FROM master.dbo.sys.databases WHERE name = N'DBNAME')
              BEGIN
                  CREATE DATABASE [DBNAME]
          END;
  </code></pre>
  
  <p>But if I run it outside of my sp, it works perfectly, which makes me think that it can be some problem related to permissions.</p>