0

I have a SQL 2008 database that is stored on the same instance, but this database is created by the user and name is stored in SQL table. How do I write a select statement using dynamic sql or is there a another way

So for example:

Main database - myDB
User database - userDB (this is stored in a myDB.dbo.tblUserDatabase)
userDB has a table called tblUserReports

I want to write something like this in dynamic sql:

SELECT * FROM userDB.dbo.tblUserReports

So tried:

declare @dbUser varchar(50)
set @dbUser = (SELECT strDBName FROM myDB.dbo.tblUserDatabase)

SELECT * FROM @dbUser.dbo.tblUserReports

2 Answers 2

2

You can do this... dynamic sql can become unmanageable very quickly so be careful.

declare @dbUser varchar(50)
set @dbUser = (SELECT strDBName FROM myDB.dbo.tblUserDatabase)

DECLARE @sql NVARCHAR(1000)
SET @sql = 'SELECT * FROM ' + QUOTENAME(@dbUser) + '.dbo.tblUserReports'

EXEC sp_executesql @sql
Sign up to request clarification or add additional context in comments.

1 Comment

Use QUOTENAME(@dbUser) for a little added protection.
1

You cannot parameterise the table name. You will have to use dynamic SQL in your client or stored procedures. It's a very unusual thing to want to do so think long & hard about if this is a good design. Maybe if you share what you are doing then you'll get some additional ideas as to how to approach your problem.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.