TSQL - Using variable as DBName for ALTER Command

  • Hello,

    Trying to tun the following in query analyzer.....

    DECLARE @xx AS nvarChar(128)

    SET @xx = (SELECT DB_NAME()) --Pick up current dbname

    ALTER DATABASE @xx

    SET RECURSIVE_TRIGGERS ON

    GO

    But get's error....

    Server: Msg 170, Level 15, State 1, Line 3

    Line 3: Incorrect syntax near '@xx'.

    Server: Msg 195, Level 15, State 1, Line 5

    'RECURSIVE_TRIGGERS' is not a recognized option.

    As if is does not recoqnize @xx as valid name. The variable is set correctly (try "SELECT @xx after setting it)

    Any idea's ????

    Thanks,

    Lars

     

  • DECLARE @xx AS nvarChar(128)

    SET @xx = (SELECT DB_NAME()) --Pick up current dbname

    exec ('ALTER DATABASE '+@xx + 'SET RECURSIVE_TRIGGERS ON')

    GO

  • Tried it.....

    DECLARE @xx AS nvarChar(128)

    SET @xx = (SELECT DB_NAME()) --Pick up current dbname

    exec ('ALTER DATABASE '+@xx+'SET RECURSIVE_TRIGGERS ON')

    GO

    Gives

    Server: Msg 156, Level 15, State 1, Line 1

    Incorrect syntax near the keyword 'ON'.

    Also tried (adding space before SET)

    DECLARE @xx AS nvarChar(128)

    SET @xx = (SELECT DB_NAME()) --Pick up current dbname

    exec ('ALTER DATABASE '+@xx+' SET RECURSIVE_TRIGGERS ON')

    GO

    Gives

    Server: Msg 156, Level 15, State 1, Line 1

    Incorrect syntax near the keyword 'SET'.

    Server: Msg 195, Level 15, State 1, Line 1

    'RECURSIVE_TRIGGERS' is not a recognized optio

    ??? What is going on ???

    Thanks Lars

  • Found solution.........

    DECLARE @xx AS nvarChar(128)

    SET @xx = (SELECT DB_NAME()) --Pick up current dbname

    exec ('ALTER DATABASE "'+@xx+'" SET RECURSIVE_TRIGGERS ON')

    GO

     

    The databasename contains blanks - so added " to the string,

    Thanks for the EXEC help

    Lars Kjeldsen

  • Lars:

    Why not use the built-in SPs to do this?  We do this sort of thing all the time, but always use the system SPs.
     
    DECLARE @vchSQLString VARCHAR(1000)
    DECLARE @vchDBName SYSNAME
    DECLARE @vchOption VARCHAR(100)
    DECLARE @vchOptionValue VARCHAR(50)
     
    SET @vchDBName = DB_NAME()
    SET @vchOption = 'recursive triggers'
    SET @vchOptionValue = 'TRUE'
    SET @vchSQLString = 'EXEC dbo.sp_dboption @dbname = ' + '''' + @vchDBName  + ''',' + '@optname = ''' + @vchOption + ''', @optvalue = ''' + @vchOptionValue + ''''
     
    EXEC (@vchSQLString)

    Sincerely,

    Allen Shannon

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

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