Visual Studio Database project: checking if SQL server login exists before creating it

JustAMartin picture JustAMartin · Jun 4, 2012 · Viewed 10.7k times · Source

When I create a Visual Studio database project for SQL 2012 and synchronise it with an existing database (using Compare Schema), I also synchronise a SQL server login. Visual Studio generates the following script for the login:

CREATE LOGIN [my_user] WITH PASSWORD = 'somesecurepass'

When I try to publish the generated SQL on a server where this login exists, sqlcmd shows me an error:

The server principal my_user already exists.

When I look at the sql script generated by Visual Studio, I see that many objects are wrapped in IF EXISTS statements, but CREATE LOGIN is not wrapped!

I tried to wrap it manually in the SQL script in the project, but then the project does not build and there is an error pointing to IF:

SQL70001: This statement is not recognized in this context.

Now how do I force Visual Studio to generate the login creation script with the IF EXISTS check and also do not lose the synchronisation abilities?

Answer

Jai picture Jai · Apr 8, 2013

Change the Build Action property of the script file (*.sql) to None. This solves the problem.

The build action property is accessed by right-clicking the sql file in solution explorer, then clicking properties. Alternatively, highlight the file in solution explorer and press 'F4'.