I am working with Microsoft SQL Server 2016 in Windows Server 2016.
I have a query with 1 parameter, string type.
select PH.project_name, PD.employee_id, E.first_name, E.last_name
from project_header PH
inner join project_detail PD on PD.project_id = PH.project_id
inner join employee E on E.employee_id = PD.employee_id
where PH.project_name = @ProjectName
order by 1, 2;
where @ProjectName is varchar(50) type.
I have to write a proc which receives 2 arguments: database name and project name:
@a_database_name varchar(100),
@a_project_name varchar(50)
I want to run the above query passing @a_project_name as parameter to the query. And I want to run the query against the database provided in @a_database_name variable using sp_executeSQL. How can I do that?
I know how to perform this task without sp_executeSQL. I want to know how to do it with sp_executeSQL?
You can use below SQL to create that procedure:
But it has SQL injection risk- if
@a_database_nameis provided contains in it";DROP DATABASE". But if you trust the system that is calling this procedure you are good to go.Or you might use below query without "use databasename" in it:
Query with sp_executesql:
Revised Answer: