Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SP_EXECUTESQL with database as variable in from clause

Is it possible to pass parameter into sp_executesql to determine the source of my query? The goal here is to recieve db name as parameter and sql text with placeholder as parameter and combine them together. I can use REPLACE probably but then I won’t get the parameter safety check.

Code:

DECLARE @my_db VARCHAR(30) = 'MyDatabase'
DECLARE @sql NVARCHAR(MAX) = N'select top 10 * from @db.dbo.table1'


exec sys.sp_executesql @stmt = @sql, @params = N'@db varchar(120)', @db = @my_db;

Result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Incorrect syntax near ‘.’.

I’m using SQL Server 2016

>Solution :

You, sort of can parametrise the database name here. Instead, define the proc name as a variable:

DECLARE @DBName sysname = N'MyDatabase'
DECLARE @Proc nvarchar(500) = QUOTENAME(@DBName) + N'.sys.sp_executesql';
DECLARE @SQL nvarchar(MAX) = N'SELECT TOP 10 * FROM dbo.table1 ORDER BY SomeColumn;'; --You need an ORDER BY for reliable results


EXEC @Proc @SQL;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading