Pergunta

Is the Pre-Deployment script (Script.PreDeployment.sql) the best place to put sql commands that create server level objects (specifically logins in my case)?

I need to create server logins for the database users in the project and this seems the only vaguely logical place to put them as everything else in the project structure (created from reversing our dev db) is database specific. I therefore just wanted to check where others store their server level commands when working with Visual Studio Database Projects.

Many Thanks.

Foi útil?

Solução

Anything you need prior to deploying your database would be in that script.

In our case, we add logins in the post deployment script. They are not needed when we deploy the database, and we decided to put all the security related commands in the same place.

IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = N'$(DefaultLogin)')
BEGIN
    BEGIN TRY
        CREATE LOGIN [$(DefaultLogin)] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
    END TRY
    BEGIN CATCH
        -- A try-catch is needed in case a user with a different name is created for the LOGIN specified.
    END CATCH
END
GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'$(DefaultLogin)')
BEGIN
    BEGIN TRY
        CREATE USER [$(DefaultLogin)] FOR LOGIN [$(DefaultLogin)] WITH DEFAULT_SCHEMA=[dbo]
        -- The db_owner role is added to the current database.
        EXEC sp_addrolemember N'db_owner', N'$(DefaultLogin)'
    END TRY
    BEGIN CATCH
        -- A try-catch is needed in case a user with a different name is created for the LOGIN specified.
    END CATCH
END

Here is the Pre and Post deployment reference.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top