WHERE clause in dynamic TSQL and prevent SQL Injection - where-clause

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.

Related

Can we do dynamic SQL in From Clause in a Select Query?

Can the select query inside a from clause be a dynamic sql?
For example
DECLARE #sql NVARCHAR(MAX)
SET #sql='SELECT * table'
SELECT t.*, a+b AS total_sum
FROM
(
EXEC (#sql)
) t
If the above is not possible, how can we achieve this functionality?
Of course the above query result in Error when run in sql server.
Thank you for the help.
In order to use dynamic table in from clause , you must run command EXEC(#sql) outside :
In your above example :
DECLARE #sql NVARCHAR(MAX)
DECLARE #dynamicSql NVARCHAR(MAX)
SET #sql='SELECT * table'
SET #dynamicSql ='SELECT t.*, a+b AS total_sum
FROM
(
'+#sql+'
) t'
EXECUTE sp_executesql #dynamicSql
In SQL Server, a SQL statement is compiled the first time the database sees it. This means that anything that can change the code being generated can't be a parameter. Which in turn means that you can't use parameters for...
table names
join expressions
column names
where clauses
order by clause
In fact, you could say that you are more or less limited to using parameters for...
Literal values in comparisons MyColumn = #Param1
Literal values in select statements SELECT #Param2
Literal values in insert/update statements SET Column = #Param3
Top, limit, and fetch clauses SELECT TOP #Param4
As mentioned elsewhere, the work-around is to create your SQL as a string and then pass that string to sp_executesql.
Deep notes:
SQL is normally compiled into an intermediate language. This intermediate language can be viewed as XML. See "execution plans" for more information.
In SQL Server 2014, stored procedures can be converted into C++ code and then compiled to machine language. There are a lot of restrictions when doing this that are too much to discus here.

View results of Stored Procedure

I have a stored procedure that executes a dynamically built string.
It unions several select statements from a constantly changing schema on another server I have no control over (hence the dynamic string). I want to be able to access the results of this procedure from a view, but this is where I get stuck.
I created a stored procedure (code below) which outputs my results to a table, but I want to be able to perform joins, etc. so it would be really convenient if there was some way to wrap this into a view- I'm thinking a table valued function, but I haven't quite figured out how to get the dynamic SQL into a function... any help is appreciated!
CREATE PROCEDURE [dbo].[usp_test]
AS
SET NOCOUNT ON;
DECLARE #sql VARCHAR(MAX)
SELECT #sql = ISNULL(#sql+'
','')+'SELECT TOP (900) *
FROM OPENQUERY(Linked_Server,
'SELECT col1, col2, col3
FROM dbo.'+ tableName+'
+'
UNION' FROM dbo.ls_views
--dbo.ls_views is a view with the pertinent views/table names from the other server.
Set #sql = #sql+ '
Select top (0) ''1'', ''2'',''3'' from sys.tables '
--last select statement is to end multiple unions... not sure if there is a better way, but this works.
--PRINT (#sql);
--EXEC (#sql);
EXECUTE sp_Executesql #sql
GO
Can you have SQL Agent execute this periodically and dump the results into another table/set of tables in your db?
Then you could use it as a straight join in whatever query you want.

SQL: Building where clause

Is there a way to get build a WHERE clause on the fly in a sql statement?
This code is within a Stored Procedure. I have x amount of parameters and each parameter's default value is NULL
SELECT *
FROM MyTable m
WHERE
IF(NOT(#Param1 IS NULL))
m.Col1 = #Param1
END IF
AND
IF(NOT(#Param2 IS NULL))
m.Col2 = #Param2
END IF
[EDIT:] I'm running SQL server 2005.
[EDIT:] The number of parameters are fixed, but can have a NULL value. If a parameter has a NULL value it shouldn't be included in the WHERE clause. Each parameter also correlates to a specific column.
Isn't this equivalent to the following, without any dynamic behavior in it?
SELECT *
FROM MyTable m
WHERE
(#Param1 IS NULL OR m.Col1 = #Param1)
AND
(#Param2 IS NULL OR m.Col2 = #Param2)
Or is there a possibility that the columns themselves might be missing?
Assuming SQL Server 2005+ syntax because the database wasn't specified... Highly recommended reading before addressing the query: The curse and blessings of dynamic SQL
DECLARE #SQL NVARCHAR(4000)
SET #SQL = N'SELECT m.*
FROM MyTable m
WHERE 1 = 1 '
SET #SQL = #SQL + CASE
WHEN #param1 IS NOT NULL THEN ' AND m.col1 = #param1 '
ELSE ' '
END
SET #SQL = #SQL + CASE
WHEN #param2 IS NOT NULL THEN ' AND m.col2 = #param2 '
ELSE ' '
END
BEGIN
EXEC sp_executesql #SQL,
N'#param1 [replace w/ data type], #param2 [replace w/ data type]'
#param1, #param2
END
You may be forced to use dynamic sql whether you're using a stored proc or not. Before you implement this stored proc, think about a few things.
Are the parameters themselves dynamic? Would you use 2 parameters one call, 10 the next? If this is the case you will need to create a ton of "placeholder" stored proc parameters that may not be used every call. What if you define 10 placeholder parameters but then need 11? This is not clean. Maybe you could use some sort of array parameter....
If parameters are dynamic, you will be forced to use dynamic SQL within your proc. This opens you up to injection attacks. You will have to manually escape all input within your stored proc. Using dymamaic sql in a proc defeats one of the main reasons for using procs.
If parameters are truly dynamic, I may actually favor generating sql from the code rather than the stored proc. Why? If you generate from the code you can use the ADO library to escape the input.
Just make sure you do something like....
sql = "select * from table where colA=#colA"; //dyanmically generated
SQlCommand.Parameters.add("#colA", valueA);
And not....
sql = "select * from table where colA=" + valueA; //dyanmically generated the wrong way
Also a 3rd thing to think about. What if the data type of the parameters is dynamic? Stored procs start to fall apart because they are a defined interface. If your operations do not conform to a interface, trying to squish them into a pre-set interface is going to be ugly.
If you're making some sort of open-ended graphical query tool, this situation will pop-up. Most of the time your data access will conform to an interface, but when it doesn't..... stored procs may not be the way to go.

how to concatenate varying stored procedure parameters

please help me with writing this search sql stored procedure
procedure may have different number of parameters at different time
so could any body help me with writing this query. I don't know how to concatenate parameters.
i am new to stored procedure
CREATE PROCEDURE searchStudent
-- Add the parameters for the stored procedure here
#course int=null,
#branch int=null,
#admissionYear varchar(max)=null,
#passingYear varchar(max)=null,
#userName varchar(max)=null,
#sex varchar(max)=null,
#studyGap varchar(max)=null,
#firstName varchar(max)=null,
#lastName varchar(max)=null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE query STR DEFAULT null
IF #course IS NOT NULL
THEN query=
SELECT * FROM [tbl_students] WHERE
END
GO
please complete the query so that it can have parameters which are having values and can search from database on the basis of parameters value. But parameter may vary every time depends on search criteria.
You would probably need to use Dynamic SQL to achieve this. First of all I would highly recommend reading this excellent article. http://www.sommarskog.se/dynamic_sql.html
You're dynamic sql would be something like this;
Declare #query varchar(max)
Set #query = 'Select * From dbo.MyTable Where '
If #Course Is Not Null
Begin
Set #query = #query + 'Course = ' + Convert(varchar(10), #Course)
end
If #Branch Is Not Null
Begin
Set #query = #query + ' and Branch = ' + Convert(varchar(10), #Branch )
end
This is only an example! You will need to build in some checks to ensure that you have one (and only one) Where clause, you must ensure that the integer values are converted to string values correctly. You must also check that the parameters don't have any special characters that could break the dynamic sql - like an apostrophe (')
Using dynamic SQL can be painful and very difficult to get right.
Good luck!
The key with a dynamic search conditions is to make sure an index is used, instead of how can I easily reuse code, eliminate duplications in a query, or try to do everything with the same query. Here is a very comprehensive article on how to handle this topic:
Dynamic Search Conditions in T-SQL by Erland Sommarskog
It covers all the issues and methods of trying to write queries with multiple optional search conditions. This main thing you need to be concerned with is not the duplication of code, but the use of an index. If your query fails to use an index, it will preform poorly. There are several techniques that can be used, which may or may not allow an index to be used.
here is the table of contents:
Introduction
The Case Study: Searching Orders
The Northgale Database
Dynamic SQL
Introduction
Using sp_executesql
Using the CLR
Using EXEC()
When Caching Is Not Really What You Want
Static SQL
Introduction
x = #x OR #x IS NULL
Using IF statements
Umachandar's Bag of Tricks
Using Temp Tables
x = #x AND #x IS NOT NULL
Handling Complex Conditions
Hybrid Solutions – Using both Static and Dynamic SQL
Using Views
Using Inline Table Functions
Conclusion
Feedback and Acknowledgements
Revision History
Sorry, I am having trouble understanding what you are asking. Do you mean the consumer of the sproc may specify some arbitrary subset of the parameters and you want to filter on those?
Assuming the above you have 2 options.
1.
use a where clause something like this:
WHERE ([tbl_students].firstName = ISNULL(#firstname,firstName)
AND ([tbl_students].lastName = ISNULL(#lastName ,lastName )
etc.
What this does is check if your parameter has a value, and, if so, it will compare it to the column. If the param is null, then it will compare the column to itself, which will never filter anything out.
use dynamic sql in your sproc and just include the line of the where clause you want if the param is not null.

Using Parameter Values In SQL Statement

I am trying to write a database script (SQL Server 2008) which will copy information from database tables on one server to corresponding tables in another database on a different server.
I have read that the correct way to do this is to use a sql statement in a format similar to the following:
INSERT INTO <linked_server>.<database>.<owner>.<table_name> SELECT * FROM <linked_server>.<database>.<owner>.<table_name>
As there will be several tables being copied, I would like to declare variables at the top of the script to allow the user to specify the names of each server and database that are to be used. These could then be used throughout the script. However, I am not sure how to use the variable values in the actual SQL statements. What I want to achieve is something like the following:
DECLARE #SERVER_FROM AS NVARCHAR(50) = 'ServerFrom'
DECLARE #DATABASE_FROM AS NVARCHAR(50) = 'DatabaseTo'
DECLARE #SERVER_TO AS NVARCHAR(50) = 'ServerTo'
DECLARE #DATABASE_TO AS NVARCHAR(50) = 'DatabaseTo'
INSERT INTO #SERVER_TO.#DATABASE_TO.dbo.TableName SELECT * FROM #SERVER_FROM.#DATABASE_FROM.dbo.TableName
...
How should I use the # variables in this code in order for it to work correctly?
Additionally, do you think my method above is correct for what I am trying to achieve and should I be using NVARCHAR(50) as my variable type or something else?
Thanks
There is probably a better way to do this, but what you are probably trying to do in your example is what's called dynamic SQL where you treat the statement as a string and the execute it. This would be section #2 here:
http://www.mssqltips.com/tip.asp?tip=1160
There are some major downsides to dynamic SQL. You see a couple other approaches that might be better in that article.
If you want to execute a dynamically generated query then you have to use sp_ExecuteSQL
HTH
For the nvarchar(50) - you'd be better using sysname. This is a synonym in SQL Server (for nvarchar(128)) and represents the maximum length of an object identifier.
have a look at http://msdn.microsoft.com/en-us/library/ms188001.aspx - sp_executesql takes a parameter that is a string and executes the sql in that string. so you'd need to concatenate #SERVER_FROM and other params with the INSERT INTO part to make the entire sql statement, and then pass to sp_executesql.
nvarchar(50) is fine, unless your server/database names are longer than that :)
You can create the select statement by concatenating all the information together and then use sp_executesql
so:
sp_executesql 'INSERT INTO ' + #SERVER_TO + '.' + #DATABASE_TO +
'.dbo.TableName SELECT * FROM ' + #SERVER_FROM + '.' +
#DATABASE_FROM+'.dbo.TableName'
I like to make templates for dynamic SQL things like this - it's a lot easier to maintain complex statements and also sometimes easier to handle nested quotes - and definitely easier when terms need to be repeated in multiple places (like column lists):
DECLARE #sql AS nvarchar(max);
SET #sql = 'INSERT INTO {#SERVER_TO}.{#DATABASE_TO}.dbo.TableName
SELECT *
FROM {#SERVER_FROM}.{#DATABASE_FROM}.dbo.TableName'
SET #sql = REPLACE(#sql, '{#SERVER_TO}', QUOTENAME(#SERVER_TO))
SET #sql = REPLACE(#sql, '{#DATABASE_TO}', QUOTENAME(#DATABASE_TO))
SET #sql = REPLACE(#sql, '{#SERVER_FROM}', QUOTENAME(#SERVER_FROM))
SET #sql = REPLACE(#sql, '{#DATABASE_FROM}', QUOTENAME(#DATABASE_FROM))
EXEC(#sql)