Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2004
    Posts
    3

    Unanswered: USE when DB name not known in advance

    NOTE: I am using MS-SQL 2K

    I have a SQL script that needs to change from a particular DB to the Master DB (to grant EXECUTE permissions to a few SPs in the Master DB), then change back to the original DB. I will not know at design time what the DB name is.

    What I am trying to do is something like this:

    Code:
    Use Master
    GO
    Grant EXECUTE on sp_OACreate TO  C2SRolePowerUsers
    GO
    Declare @DBName varchar(32)
    EXECUTE xp_instance_regread 'HKEY_LOCAL_MACHINE', 'SOFTWARE\ODBC\ODBC.ini\MyDSNName', 'Database', @param = @DBName OUTPUT
    Use @DBName
    GO
    The problems:

    1) I have to do this in a single pass using ADO and the script. The reason is that it is part of a generic routine, looping through a list off commands, and cannot perform one command, change the DB reference via ADO, then change back in separate ADO commands.

    2) It fails on the second USE command.

    I have looked to see if there is some sort of "EVAL()" function, or a stored procedure to change the current DB. No luck.

    Any suggestions?

    Thanks,


    __________________
    Bob Rouse
    Comsquared, Inc.

  2. #2
    Join Date
    Feb 2004
    Location
    In front of the computer
    Posts
    15,579
    Provided Answers: 54
    Granted this is somewhat deviant, but:
    Code:
    EXECUTE ('USE Master GRANT EXECUTE ON sp_OACreate TO  C2SRolePowerUsers')
    -PatP

  3. #3
    Join Date
    Nov 2002
    Location
    Jersey
    Posts
    10,322
    Code:
    SELECT db_name()
    Brett
    8-)

    It's a Great Day for America everybody!

    dbforums Yak CorralRadio 'Rita
    dbForums Member List
    I'm Good Once as I ever was

    The physical order of data in a database has no meaning.

  4. #4
    Join Date
    Dec 2004
    Posts
    3
    Quote Originally Posted by Brett Kaiser
    SELECT db_name()
    This just gets me the current database name (which would be Master). If executed to get the DB name before changing to Master (such as by "Set @DBName = DB_NAME()"), the GO command wipes out the variable. Regardless, it doesn't change the current selected DB. Thanks anyway.

    Quote Originally Posted by Pat Phelan
    Granted this is somewhat deviant, but:
    Code:
    EXECUTE ('USE Master GRANT EXECUTE ON sp_OACreate TO  C2SRolePowerUsers')
    -PatP
    Deviant or not, it works. Thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •