Reputation: 1421
I need to execute result (already in form of SQL) itself of an SQL query to get the final result.
So, it should be like, in first query I execute
Select Top(1) RequiredQuery as ReqQry from EPMaster
I'll get another query in result in ReqQry
that will then be executed in form another query to get the final result.
The second query will also require some parameters to be passed at where clause, like when I do:
Select Top(1) RequiredQuery as ReqQry
from EPMaster
--ReqQry after its execution returns:
Select Top(1) (FirstName + ' ' + LastName) as FullName
from DPMaster
where DmID = @DomainID and PnID = @PersonID
I'll be passing the Params @DomainID
and @PersonID
from my C# project's DAL layer.
So I guess it should be done with the help of a stored procedure.
-----------------More Explanation-------------
Here, one SQL statement is executed to get the next SQL statement which will be the resultant of the former statement. When you execute 1st query, you get 2nd query in result, which you execute again to get the final result
The second query needs 2 parameters to execute that are @DomainID
and @PersonID
which will be passed by me from my C# Project. So, if I make a stored procedure for handeling all this and pass the required parameters, along with the 1'st query from my project, it should first execute 1st query then execute 2nd query (with parameters PersonID
and DomainID
) that was received as result of 1st query, after which I get the final result.
Upvotes: 2
Views: 1859
Reputation: 13844
Declare @SQL as nvarchar(MAX);
SET @SQL = (Select Top(1)RequiredQuery as ReqQry from EPMaster);
EXEC (@SQL);
Upvotes: 0
Reputation: 7695
You should use Dynamic SQL, to get running the returned nvarchar(max) query string from the first procedure / query.
Edit:
DECLARE @ResultOfTheFirstQuery nvarchar(max)
SELECT @ResultOfTheFirstQuery = (Select Top(1)RequiredQuery
as ReqQry from EPMaster)
exec sp_executeSql @ResultOfTheFirstQuery
Or if you need a complex logic, you can write an other SP, which can heve a return value:
DECLARE @ResultOfTheFirstQuery nvarchar(max)
SELECT @ResultOfTheFirstQuery = FirstStoredprocedure @params
exec sp_executeSql @ResultOfTheFirstQuery
Here is an already well answered question how to get the paramater return. You can use RETURN
or OUTPUT
parameter.
Here is how to use the sp_executeSql
Upvotes: 2