I have a long stored procedure that starts with the following statement:
IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = N'DBNAME') BEGIN CREATE DATABASE [DBNAME] END;
It is expected that it will create a database on my local server if it does not exist. The problem is that almost all this time occurs in this part of the stored procedure and does not create it, which then interferes with other code from the same procedure. On the other hand, in very rare cases, it creates a database. My question is: is there a better way to check if a DB exists, because I have already tried at least 10.
Other ways I've tried:
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;
But if I run it outside of my sp, it works fine, which makes me think that this may be a rights issue.
source share