Dynamic query inside a SQL scalar function - sql

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?

Related

Insert string into SQL query as plain text in stored procedure

I'm trying to write a stored procedure in SQL Server that checks if search input exists in a column.
SELECT *
FROM Product
WHERE #Type LIKE #SearchResult
My problem is that when I fetch #Type from user's input, it comes as a string in SQL therefore syntax is wrong and it returns NULL.
Is there a way to get rid off single quotations or convert it to plain text in SQL?
So if #Type is "ProductName" it would appear in SQL as
SELECT *
FROM Product
WHERE ProductName LIKE #SearchResult (no single quotes around `ProductName`)
You have to use dynamic SQL to replace anything other than a constant in a query:
DECLARE #sql NVARCHAR(MAX);
SET #SQL = 'SELECT * FROM Product WHERE #Type LIKE #SearchResult';
SET #SQL = REPLACE(#SQL, '#Type', #Type);
exec sp_executesql #sql,
N'#SearchResult NVARCHAR(MAX)',
#SearchResult=#SearchResult;
You can still pass the #SearchResult value using a parameter.

Dynamically get all parameter values in stored procedure

Is there any way to get all parameter values from a stored procedure dynamically?
In other words, iterate through all parameters in one stored procedure to get their values into one string. This is for a unified logging process for a bunch of stored procedures.
I can get the names of parameters:
SELECT PARAMETER_NAME
FROM INFORMATION_SCHEMA.PARAMETER
WHERE SPECIFIC_NAME = 'procedure_name';
Also, I tried to use dynamic SQL commands. I've generated a command with included parameter, but EXEC can't execute command.
#cmd = 'SELECT '#UserID' + CONVERT(NVARCHAR(MAX), #UserID)
+ '#Date' + CONVERT(NVARCHAR(MAX), #Date)'
EXEC #cmd
Is there any way to do this besides manually generating a list of parameter values for each stored procedure?
Since SQL Server 2014 there is sys.dm_exec_input_buffer a table valued function with an output column event_info that gives the full execution statement (including parameters).
I use this for error logging in stored procedures.
For example:
--include this inside the stored procedure
declare #statement nvarchar(max)
select #statement = event_info
from sys.dm_exec_input_buffer(##spid, current_request_id())
--this will print whatever you called the procedure with (including parameters)
print #statement
-- if you want to parse just the parameters from the statement, it can be done like this
declare #proc_name varchar(128) = object_name(##procid)
declare #param_idx int = charindex(#proc_name, #statement) + len(#proc_name)
declare #param_len int = len(#statement) - #param_idx
declare #params nvarchar(max) = right(#statement, #param_len)
select #params

sql server parameter size overloading

i am calling a stored procedure from my ASP.NET application. the stored procedure takes one parameter. the value that i am providing from my WEB Form is too large that it did not fully loading in variable of sql server. the data type of my sql server parameter is nvarchar(max) and the data type in my ASP.NET application is string.
the stored procedure is as below
Create procedure p_getProducts
#nm_emp nvarchar(max)
AS
BEGIN
select * from tblProduct where nm_user in(convert(nvarchar(max),#nm_emp));
END
please tell me which sql server data type i should use to overcome this problem.
Thanks.
For what I could suppose from your code, you should work with dynamic-sql and not using directly the parameter as value for the IN clause. Try with this proc.
Create procedure p_getProducts
#nm_emp nvarchar(max)
AS
BEGIN
DECLARE #SQL NVARCHAR(MAX);
SELECT #SQL = N'select * from tblProduct where nm_user in(' +
#nm_emp + N')'
EXEC sp_executeSQL #SQL

Execute a result in SQL Server using a stored procedure

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);

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.