Execute a result in SQL Server using a stored procedure - sql

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.

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

Declare #SQL as nvarchar(MAX);
SET #SQL = (Select Top(1)RequiredQuery as ReqQry from EPMaster);
EXEC (#SQL);

Related

query inside the variable

Is it possible in SQL to use a variable to store query.
For example to save time when subquery is used multiple times inside the main query.
Example:
DECLARE #my_query as varchar(250) = select x from my_table where my_table = y.your_table
SELECT
a,b,c,(#my_query),d,e,f
FROM my_table_1
Is it possible in SQL to use a variable to store query.
Depend on your definition of "query". If you mean store the text which we use to execute the command, then the answer is YES. If you mean an object type query, then the answer is not - since there is no data type that fit this.
What I mean is that a variable can store a value which is string. The string can be any query command that you want. Therefore, you can store for example the text "select col1,col2 from table1".
Next you need to ask how can we use this text in order to execute it as part of a query, which is done using dynamic query.
We can execute a text of a query using the build-in stored procedure sp_executesql, which is build for such needs.
For example:
-- DECLARE VARIABLE
DECLARE #MyQuery NVARCHAR(MAX)
-- SET the value of the variable
SET #MyQuery = 'SELECT ''Yes I can'''
-- Executing a dynamic query
EXECUTE sp_executesql #MyQuery
Here is another example which look more close to your question:
-- First let's create a table
CREATE TABLE T(ID INT)
INSERT T(ID) VALUES (1),(2)
GO
-- And here is what you sked about:
-- DECLARE VARIABLE
DECLARE #MyQuery NVARCHAR(MAX)
-- SET the value of the variable
SET #MyQuery = 'select ID from T where ID = ''1'''
-- Let's combine the text to a full query now
DECLARE #FullQuery NVARCHAR(MAX)
SET #FullQuery = '
SELECT
ID,(' + #MyQuery + ')
FROM T
'
PRINT #FullQuery
-- Executing a dynamic query
EXECUTE sp_executesql #FullQuery
NOTE! Your specific sample of query will return error, which is not related to the question "Is it possible in SQL to use a variable to store query". This is a result of the "query" is not well formatted.
Important! It is HIGHLY recommended to read the document about this stored procedure and learn a bit more of the options it provides us.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-ver15

Dynamic query inside a SQL scalar function

I want to invoke a dynamic query inside a Scalar function. I tried using EXEC and sp_executesql, but it is not found success. Then I went for OPENQUERY, But it do not accept dynamic parameters.
Here is my SQL code
DECLARE #query varchar(max) = 'SELECT COUNT('+#FromCol+') from '+#FromTable+' WHERE '+#FromCol+' IN (SELECT '+#ToCol+' FROM '+#ToTable+' WHERE userId = 0)'
INSERT INTO #TempResult([rowCount])
SELECT *
FROM OPENQUERY([GREEN\SQLEXPRESS], 'Exec [MyDB].[dbo].[testSP] '+[#FromCol]) as [OpenQuery]
Here, if possible can I execute dynamic query ie, #query or pass parameter to stored procedure testSP?

sql server - fill results from executed query string in a temp table dynamically

I'm writing a stored procedure. I have a string which contains an sql query. For example:
DECLARE #sql nvarchar(max)
SET #sql = (N'SELECT pkOrderID FROM Orders')
(Just to note: this isn't what the select statement looks like. This is just an example of what I mean) I then want to execute the string and put the result in a temporary table E.g. #tempTable. I know EXEC(#sql) exists but not sure if it will do me any good in this situation. The other twist is that I do not know the names of all the columns in the returned #sql so the temp table #tempTable needs to be created dyanmically based off the return from #sql. Thanks for any help.
I think you could use SELECT INTO to do what you want but it would mean updating your string:
DECLARE #sql nvarchar(max)
SET #sql = (N'SELECT frompkOrderID INTO #tmporders FROM Orders')
then you should be able to run EXEC #sql to create the table
more information about SELECT INTO here : http://msdn.microsoft.com/en-au/library/ms188029.aspx
There is no simple way to do this. The problem with #JanR's solution is that the #tmporders table will be out of scope to the script that calls your stored procedure (ie It will produce an error like "Invalid object name '#rtmporders'"
One alternative is to use a global temp table (eg ##tmporders).
So your SP might look like this:
CREATE PROCEDURE TestSP
AS
BEGIN
SELECT pkOrderID INTO ##tmporders FROM Orders
END
GO
And the calling script might be like:
EXEC TestSP
SELECT * FROM ##temporders

Insert result of executing dynamic query into a table

I have a dynamic query #strQuery which on executing gives a result with lots of column.
I want to insert the result from this dynamic query into a temporary table .
I am doing this because I want to perform some filtering on the temporary table and get required result .
A similar question was asked on previous thread HERE
in which a temporary table is created first and then data inserted using INSERT INTO.
I want to avoid this step due to long list of columns and also the datatypes of fields is not known to me.
select * into #tmh from
exec(#strQuery)
Error Message
Incorrect syntax near the keyword 'exec'.
How to do this ? Is it possible to be done in this way ? If not , please specify some other alternative to get store the result on executing dynamic query into a table.
Thanks.
I have faced this situation before and here is what I did:
DECLARE #strQuery nVarchar(100)
SET #strQuery='SELECT * into [tempdb].[dbo].[temptable] FROM YourTable'
EXECUTE sp_executesql #strQuery
SELECT * FROM [tempdb].[dbo].[temptable]
DROP TABLE [tempdb].[dbo].[temptable]
It works fine. Don't ask me why a FQ table name and not #temptable. I have no idea. It does not work. The only way I could get it working was using [tempdb].[dbo].[temptable]
proceed like this
select t1.name,t1.lastname from(select * from table)t1.
where "select * from table" is your dyanmic query. which will return result which you can use as temp table t1 as given in example .
You can use variables in your current execution context, set by the Dynamic SQL with the OUTPUT option. Sample code below.
DECLARE #Amount AS MONEY
DECLARE #SQL AS NVARCHAR(1000)
SET #Amount = NULL
SET #SQL = ('SELECT #amt=100' )
EXECUTE sp_executeSQL #SQL, N'#amt MONEY OUTPUT', #amt=#Amount OUTPUT
SELECT #Amount
Yes you can make a new dynamic query containing the original query with the insert like this:
declare #strNewQuery varchar(max)
set #strNewQuery ='select * into #tmh from ('+#strQuery+') as t'
exec(#strNewQuery)
I used this to work around - with out dynamic query
This uses a table variable to receive data to procedure
Even joins can be applied to it
select * into #itemPhantom from #tbl_items_upload
select * from #itemPhantom
select #itemPhantom.itemreference from #itemPhantom left join phantom on phantom.name=#itemPhantom.PhantomName

WHERE clause in dynamic TSQL and prevent SQL Injection

I have a stored procedure for selecting rows. I want to pass a parameter to filtering rows dynamically like this :
Create Procedure CustomerSelectAll
#FilterExpresion NVARCHAR(MAX)
DECLARE #CMD NVARCHAR(MAX)
SET #CMD = N'SELECT * FROM dbo.Customers '+#FilterExpresion;
EXEC(#CMD)
The above code works fine, but it is at risk for SQL injection, so I want to be able pass multiple columns with any WHERE statement such as:
exec CustomerSelectAll
#FilterExpresion = N' where Name = 'abc' and family = ''xyz'''
I am not aware if you can pass the entire where clause as parameter.But from the little amount of knowledge I have, I can suggest you use a sql parser to see if the where clause has just select statements and if the answer is affirmative then you can pass the where clause to your stored procedure. Hope this is of some help.