1

can I go like this

USE SELECT databasename from databasenametable

or something similar?

rather than do the select and then put the value in the use satement? I tried brackets around the select and that didnt work. the above didnt work either. i wouldnt know what else to do

0

2 Answers 2

2

If you are using SQL Server, USE statement should get an explicit value for database name:

USE [databasename]

If you insist of doing this dynamically, you can use Dynamic Sql:

DECLARE @db AS NVARCHAR(258);
SET @db = QUOTENAME(N'Pubs'); -- put whatever you want here..
EXEC(N'USE ' + @db);
GO
1
  • so i cant do what im asking. i got a bunch of db's and i know which one i want to use based on a query. i want to put that query in my use statement, rather than give it an explicit value
    – dwarf
    Nov 28, 2013 at 21:23
0

If you only need to execute one statement in another database, another alternative might be something like :

declare @sql nvarchar(500)
declare @yourDatabaseName nvarchar(50) = 'junk'
declare @yourQuery NVARCHAR(200) = 'select * from someTable'
set @sql = @yourDatabaseName + '..sp_executesql N''' + @yourQuery + ''''
EXEC (@sql) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.