IF EXISTS query problem

  • What is wrong with this query..

    IF exists (SELECT dbid FROM sysdatabases WHERE name = 'ACID')

    BEGIN

    USE ACID

    CREATE USER [nl\sqlserver]

    EXEC sp_addrolemember 'MailUsers', 'nl\sqlserver'

    END

     

    For some reason, even though the IF exists statement is false (ie, 'ACID' does not exist on the sql server!) it still tries to execute whats inside the 'begin'..'end'. It's probably something very obvious but i can't see it!

    Thank you!

  • Your USE statement inside the IF should be in a separate batch.  I would suggest putting everything inside the BEGIN...END in dynamic SQL and use EXEC.  Try this (untested):

    IF exists (SELECT dbid FROM sysdatabases WHERE name = 'ACID')

    BEGIN

        DECLARE @s-2 VARCHAR(500)

        SET @s-2 = 'USE ACID

                         CREATE USER [nl\sqlserver]

                         EXEC sp_addrolemember ''MailUsers'', ''nl\sqlserver'''

        EXEC (@s)

    END

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply