I tried the following:
declare #var2 nvarchar(30)
declare #qsql nvarchar(100)
set #var2 = N'iddelegat'
exec ('select max('+ #var2 + ') as IDexec from delegat');
set #qsql = 'select max(#varsp) as IDspexec from delegat';
exec sp_executesql #qsql, N'#varsp nvarchar(30)', #var2;
And the result:
IDexec IDspexec
-----------------------
500038 iddelegat
I could not understand why sp_executesql does not return the same result as EXECUTE. The right returned values are only in EXECUTE statement. It seems that sp_executesql does not evaluate the string 'iddelegat' to return the column.
You cannot parameterize column names or table names when using sp_executesql. So, when you plug in the value iddelegat in the exec(), you are getting the column. When you have it as a parameter to sp_executesql, you are getting 'iddelegat' -- a string with the name of the column.
The issue of what you can parameterize is not well explained in the SQL documentation. If you dig far enough, you will get this:
Where You Can Use Parameters
You can use parameters as placeholders for literal values — for either
text or numeric values. Most commonly, parameters are used as
placeholders in search conditions for individual rows or for groups
(that is, in the WHERE or HAVING clauses of an SQL statement).
This is in an obscure part of the documentation, but it has the correct general idea.
To help further understand this, the SQL engine can compile queries with parameters to get the execution plan. To do this, it needs to know the actual columns and tables in the query. Extra values -- parameters -- can be plugged in after the compilation step.
You can't parameterise column names.
Your attempt is basically the same as doing MAX(N'iddelegat') not MAX(iddelegat)
The only way of using these in dynamic SQL is to concatenate them into the string directly.
You should use the quotename function if doing so to mitigate against SQL injection possibilities.
See The curses and blessings of dynamic SQL
Related
Is there a way to create a dynamic temp table. Below sql code is declaring a variable #tic. I am planning to insert contents from table1 to temp table #df. So instead of giving directly as #df, I am passing as a variable. But below is code is not successful. Can anyone help me here?
declare #tic as varchar(100) = 'df'
select *
into '#' + #tic from (
select * from [dbo].[table1])
select * from #df
Is there a way? Well, I think of the answer as "yes and no and maybe".
As far as I know, there is no way to do this using a local temporary table. As Stu explains in the comment, you would need dynamic SQL to define the table name and then the table would not be visible in the outer scope, because it is a local temporary table.
The "yes" is because one type of temporary table are global temporary tables. These are tables that persist across different scopes. And they are defined using ## instead of # as the prefix. So this works:
declare #tic as varchar(100) = 'df'
declare #sql nvarchar(max);
set #sql = 'select * into ##' + #tic + ' from table1';
select #sql;
exec sp_executesql #sql;
select * from ##df;
(Here is a db<>fiddle.)
The "maybe" is because I'm quite skeptical that you really need this. Dynamic table names are rarely useful in SQL systems, precisely because they depend on dynamic SQL. Introducing dynamic names into SQL (whether columns or tables) is dangerous, both because of the danger of SQL injection and also because it can introduce hard-to-debug syntax errors.
If you are trying to solve a real problem, there might be alternative approaches that are better suited to SQL Server.
One of the product teams I manage has an abundance of queries that use dynamic sql queries injecting the table in using concatenation. While it has sanitisation, I am trying to completely remove dynamic sql.
Is there a way to parameterise the table name?
I am trying to think of how I can query a table something like:
SELECT * FROM (SELECT DISTINCT Table_Name FROM INFORMATION_SCHEMA.Tables WHERE Table_Name = :queryParam)
Is this possible?
There is no way to "properly" prevent SQL injection completely from within SQL, the calling application layer should do this prior to executing any SQL statement.
Solve the problem by using an ORM or building the code to protect yourself from SQL injection when you generate the SQL in the application code.
This feels like a classic XY problem, try to take a step back and consider that you need to protect the access to the SQL server itself rather than sanitise everything from within "after" your SQL server has been accessed.
I am trying to completely remove dynamic sql.
You can't do it without Dynamic SQL.
Is this possible?
No, it's not possible, you cannot parameterize identifiers in SQL queries.
Why?
From the Books online page for Variables, Variables can be used only in expressions, not in place of object names or keywords. To construct dynamic SQL statements, use EXECUTE.
This is the only way to do it:
DECLARE #Column SysName = N'Table_Name',
#Param NVARCHAR(128) = N'ParamValue';
DECLARE #SQL NVARCHAR(MAX)=N'SELECT *
FROM(
SELECT '+ QUOTENAME(#Column) +
'FROM INFORMATION_SCHEMA.Tables
WHERE ' + QUOTENAME(#Column) + ' = #Param
) T';
EXECUTE sp_executesql #SQl,
N'#Param NVARCHAR(128)',
#Param;
DECLARE #a varchar(max);
set #a ='''a'' OR Name like ''%a'';';
--Why the below query not working
Select TOP 10 * FROM Member where Name = #a
-- The query below was executed to make sure that the query above
being constructed properly
print 'SQL: Select TOP 10 * FROM Member where Name ='+ #a
--SQL: Select TOP 10 * FROM Member where Name ='a' OR Name like '%a';
Correct me if im wrong, SQL injection wont work in Stored Procedure is due to some precompiled factor but the above scenario was tested in query statement instead of Stored Procedure. Why still not working?
I'm not sure why you think that would work. #a is a varchar variable, so Select TOP 10 * FROM Member where Name = #a finds rows where Name is equal to the value of that variable.
If you want SQL-Server to take the value of #a and insert it into the query as code, then you need to use sp_executesql (analogous to eval in languages like Bash and Python and JavaScript):
EXECUTE sp_executesql 'Select TOP 10 * FROM Member where Name = ' + #a
SQL Injection occurs when data is confused for and interpreted as code.
This does not happen in your scenario since parameter or variable values are not directly interpreted as code - they're only at risk of being interpreted as code if you construct new code by combining strings and these parameter/variable values and then pass the entire constructed string to the system and ask it to interpret the entire string as code - via exec, sp_executesql or other such means.
Look there is no name ending with 'a'. Try like
Select TOP 10 * FROM Member where Name ='a' OR Name like '%a%'
Updated
Microsoft handle SQL injection for SQL parameters.
I am getting the following error when I execute my stored procedure:
Msg 102, Level 15, State 1, Line 6Incorrect syntax near '2011'.(1 row(s) affected)
Here is the stored procedure:
ALTER PROCEDURE [dbo].[DeliveryFileNames]
AS
BEGIN
SET NOCOUNT ON;
declare #SQL nvarchar(4000)
Create Table #DelivTemp(
Style nvarchar(50),
Material nvarchar(50),
Filename nvarchar(100),
delivered_date date)
set #SQL=
N'insert into #DelivTemp
Select distinct Style,Material,filename
from OPENQUERY(GCS_PRODUCTION,
''SELECT LEFT(FILENAME,locate(''''_'''',FILENAME)-1)as Style,
substring_index(filename,''''_'''',2)as Material,filename,
delivered_date FROM view_delivery_log
where delivered_date > ''2011%'' order by Style '')'
exec (#SQL)
drop table dbo.DelivFN
Select * into dbo.DelivFN
from #DelivTemp
END
I am using OpenQuery to update a SQL table from a linked server on SQL Server 2008 R2.
I know that the underscore is a real issue, but I have tried a plethora of options including \, % and both single and double quotes.
Regardless I am getting the same result. I can run the query independently of the stored procedure and achieve the correct results. The filename field referenced several times is formatted 00000000_ABC4_A.png. I am using the underscore to identify the components of the file name that I need for my reporting purposes.
In addition to the the logical error of your date comparison using the % that the others have pointed out, your current issue is a syntactical error.
Since you've got a dynamic sql statement contained within another dynamic sql statement... you'll need to double-escape all of your single quotes... which you did in most of the query, except for the following line:
where delivered_date > ''2011%'' order by Style '')'
Properly escaped, would be:
where delivered_date > ''''2011%'''' order by Style '')'
Which raises the question... why are you building up the string to execute dynamically, instead of just calling the statement directly?
It's the syntax of ''2011%''. This is not a valid date. % being a wildcard means the compiler can't know what to compare against in the WHERE clause. You'd need to use an actual date: i.e. ''2011_01_01'' so the compiler can know what to compare against
I believe the stored proc exec runs under a different session, therefore you won't have access to the temp table anyway. So, it won't matter if you get that sql statement to run. You could always use YEAR(delivered_date) > 2011.
Another approach would be to use the fqn for the linked server to select into and bypass the temp table all together:
SELECT LEFT(FILENAME,locate('_',FILENAME)-1)as Style,
substring_index(filename,'_',2)as Material,filename,delivered_date
FROM [linked_server_name].[db_name].[dbo].view_delivery_log
into dbo.DelivFN
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Need help in dynamic query with IN Clause
I am using SQL server 2008 and this is the problem that I am facing. I have a table named Cars with a column Company. Now I have a stored procedure that looks something like this
CREATE PROCEDURE FindCars (#CompanyNames varchar(500))
AS
SELECT * FROM Cars WHERE Company IN (#CompanyNames)
I tried something like this and failed
DECLARE #CompanyNames varchar(500)
SET #CompanyNames = '''Ford'',''BMW'''
exec FindCars #CompanyNames
I dont get any rows returned. When I do the following
DECLARE #CompanyNames varchar(500)
SET #CompanyNames = '''Ford'',''BMW'''
Select #CompanyNames
I get the following result
'Ford','BMW'
and if I replace this value in the select statement inside the stored procedure, it works
SELECT * FROM Cars where Company in ('Ford','BMW')
Thus I think that the stored procedure seems to be treating 'Ford','BMW' as one string rather than an array. Could someone please help me with this. How do I dynamically construct the string/array required in the IN clause of the select statement inside the stored procedure.
You are right, you created one string, and that is being processed as a list of strings that contains one string. The commas are just characters in that one string. The only equivilent to an array in SQL Server is a table.
For example; WHERE x IN (SELECT y FROM z).
For this reason many people create a SPLIT_STRING() function that returns a table of items from a given comma delimitted string...
WHERE x IN (SELECT item FROM dbo.split_string(#input_string))
There are many ways to implement that split string. Some return strings, some cast to integers, some accept a second "delimiter" parameter, etc, etc. You can search the internet for SQL SERVER SPLIT STRING and get many results - Including here in StackOverflow.
An alternative is to use dynamic SQL; SQL that writes SQL.
SET #sql = 'SELECT * FROM x WHERE y IN (' + #input_string_list + ')'
SP_EXECEUTESQL #sql
(I recommend SP_EXECUTESQL over just EXEC because the former allows you to use parameterised queries, but the latter does not.)