0

I have a simple requirement where I need to replace a variable with the database name coming from another table.

I have a table called config setting

Key value

ClubcardDB ClubardDetailsDB

Code

Declare @Value varchar(100)
select @Value= value configsetting where Code=’ ClubcardDB’
Select top 10 * from  [@Value].[dbo].[ClubcardDetails]

it is giving an error: Invalid object name '@Value.dbo.ClubcardDetails'.

I do not want to build and dynamic query..

2
  • 5
    You would need dynamic sql for this. Commented Mar 11, 2019 at 13:56
  • Why did not you want to build dynamic query Commented Mar 11, 2019 at 14:04

2 Answers 2

0

Try to use SQLCMD Mode. In SSMS, click Query -> SQLCMD Mode:

:setvar dbname "YourDB" 

SELECT * FROM $(dbName).dbo.YourTable

Read more about SQLCMD.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is a working example that I made on my machine:

Declare @Value varchar(100)='Test'
DECLARE @SQL NVARCHAR(MAX)

SET @SQL='Select * from ' + QUOTENAME(@Value) + '.[sys].[all_columns];'
EXECUTE sp_executesql @SQL

A slightly safer method as it verifies the value is actually a database name:

Declare @Value varchar(100)='Test'
DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL='Select * from ' + QUOTENAME(name) + '.[sys].[all_columns];'
FROM master.dbo.sysdatabases
WHERE name=@Value

EXECUTE sp_executesql @SQL

5 Comments

You'll want to at least handle SQL Injection here. This is just a security vulnerability as it is.
While that is true, if you can't control the value in your own configuration table, you have bigger issues.
I still suggest properly using QUOTENAME at least. A bracket can easily be escaped by someone malicious. For example SET @Value = N'master].sys.objects; CREATE LOGIN t WITH PASSWORD=''1'',CHECK_POLICY=OFF,CHECK_EXPIRY=OFF;--'
Really? What didn't work when you tried '...FROM ' + QUOTENAME(@value) + '.sys...'?
@Larnu I didn't remove the [] in the literal; answer updated

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.