SQLServerCentral.com / SQL Server 2008 / T-SQL (SS2K8) / forming a dynamic query / Latest PostsInstantForum.NET v2.9.0SQLServerCentral.comhttp://www.sqlservercentral.com/Forums/notifications@sqlservercentral.comSun, 02 Aug 2015 16:47:30 GMT20RE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspx[quote][b]Sean Lange (5/7/2014)[/b][hr][quote][b]Jeff Moden (5/6/2014)[/b][hr][quote][b]Sean Lange (5/1/2014)[/b][hr]The first and the biggest issue is this is wide open to sql injection.[/quote]In most cases, I'd strongly agree with you but... with two DATE, one INT, and one CHAR(1) parameters, I'd have to say that SQL Injection is impossible for the given code.As to whether or not dynamic SQL is required for the original query or not goes, I'd have to agree with you and the others... NOT. :-)[/quote]Yes I even said as much in my post. However, the OP is struggling with a concept here and we all know what happens when you have dynamic sql that is working and somebody comes along and adds another value to the mix. At some point they will add a varchar to the mix and because the initial work was done in a format that allows it this will be wide open. Or the other side of that is that they will use this same technique on another process because it worked here. I am just trying to help the OP learn a better way of doing this so that in the future their code will be safe. :-)--edit--fixed a spelling error.[/quote]Ah... understood. Thanks, Sean.Wed, 07 May 2014 12:07:19 GMTJeff ModenRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspx[quote][b]a4apple (5/7/2014)[/b][hr]I believe you can write this query without using DYNAMIC SQL. but the only part that confuses me is @CID. You specified it as integer, and you are passing a name to it.You can write something like this[code]SELECT *FROM [Transaction]WHERE Transdt BETWEEN CONVERT(VARCHAR (10),@transfrmdt,111) AND CONVERT(VARCHAR (10),@transtodt,111)AND (@Cid IS NULL OR Cid = @cid)AND (NULLIF(@Type, '') IS NULL OR [Type] = @Type)[/code][/quote]This was mentioned already more than once. This is an example of a catch-all query. They work but usually have some negative performance implications. You can read more about this type of query here.[url=http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/]http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/[/url]Wed, 07 May 2014 10:04:35 GMTSean LangeRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxI believe you can write this query without using DYNAMIC SQL. but the only part that confuses me is @CID. You specified it as integer, and you are passing a name to it.You can write something like this[code]SELECT *FROM [Transaction]WHERE Transdt BETWEEN CONVERT(VARCHAR (10),@transfrmdt,111) AND CONVERT(VARCHAR (10),@transtodt,111)AND (@Cid IS NULL OR Cid = @cid)AND (NULLIF(@Type, '') IS NULL OR [Type] = @Type)[/code]Wed, 07 May 2014 09:59:07 GMTa4appleRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxThanks Sean !Wed, 07 May 2014 09:36:09 GMThomebrew01RE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspx[quote][b]homebrew01 (5/7/2014)[/b][hr]How would the hacker pass that variable to the stored procedure ? If it's part of a form on a website, then hackers can enter character strings. But if the procedure is deeper in the application ??[/quote]Don't think about where the procedure can be accessed from. That is dangerous. Just because today the procedure isn't available from a web form doesn't mean that tomorrow it won't be. Remember that dynamic sql can be parameterized. Taking the same dynamic sql we can easily parameterize it. Now this code is injection proof. When using dynamic sql it is not hard to write code that is injection proof.[code]alter procedure IsThisVulnerable( @MyValue varchar(50)) as declare @SQL nvarchar(max) set @SQL = 'select * from sys.objects where name = @MyValue' exec sp_executesql @SQL, N'@MyValue varchar(50)', @MyValue = @MyValue goexec IsThisVulnerable ''';drop proc IsThisVulnerable--'exec IsThisVulnerable 'IsThisVulnerable'[/code]Wed, 07 May 2014 09:16:07 GMTSean LangeRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxHow would the hacker pass that variable to the stored procedure ? If it's part of a form on a website, then hackers can enter character strings. But if the procedure is deeper in the application ??Wed, 07 May 2014 08:54:50 GMThomebrew01RE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspx[quote][b]homebrew01 (5/7/2014)[/b][hr]Could someone include the "how" and "why" that dynamic SQL is vulnerable to SQL injection ?[/quote]Well because of the datatypes presented here it really isn't vulnerable to sql injection. However, whenever I see somebody executing parameters to a stored proc the lights and sirens blaze loudly because the technique is incredibly dangerous.Here is an example of dynamic sql that is very similar to the code posted in this thread.[code]create table InjectTest( SomeValue varchar(50))insert InjectTestselect 'Here I am.'goselect * from InjectTestgocreate procedure IsThisVulnerable( @MyValue varchar(50)) as declare @SQL nvarchar(max) set @SQL = 'select * from sys.objects where name = ''' + @MyValue + '''' select @SQL exec(@SQL) go--So the example here is simplified but demonstrates sql injection--Consider what happens when we execute this proc with these parameters.exec IsThisVulnerable ''';drop table InjectTest--'select * from InjectTest--Now let's get really nasty. We will use sql injection to make the proc drop itself. ;)select * from sys.objects where name = 'IsThisVulnerable'goexec IsThisVulnerable ''';drop proc IsThisVulnerable--'goselect * from sys.objects where name = 'IsThisVulnerable'[/code]Try this out on a sandbox database. This code will create a table and proc. Then actually remove all those object using sql injection.Wed, 07 May 2014 08:38:28 GMTSean LangeRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxCould someone include the "how" and "why" that dynamic SQL is vulnerable to SQL injection ?Wed, 07 May 2014 08:06:45 GMThomebrew01RE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspx[quote][b]Jeff Moden (5/6/2014)[/b][hr][quote][b]Sean Lange (5/1/2014)[/b][hr]The first and the biggest issue is this is wide open to sql injection.[/quote]In most cases, I'd strongly agree with you but... with two DATE, one INT, and one CHAR(1) parameters, I'd have to say that SQL Injection is impossible for the given code.As to whether or not dynamic SQL is required for the original query or not goes, I'd have to agree with you and the others... NOT. :-)[/quote]Yes I even said as much in my post. However, the OP is struggling with a concept here and we all know what happens when you have dynamic sql that is working and somebody comes along and adds another value to the mix. At some point they will add a varchar to the mix and because the initial work was done in a format that allows it this will be wide open. Or the other side of that is that they will use this same technique on another process because it worked here. I am just trying to help the OP learn a better way of doing this so that in the future their code will be safe. :-)--edit--fixed a spelling error.Wed, 07 May 2014 07:19:30 GMTSean LangeRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspx[quote][b]Jeff Moden (5/6/2014)[/b][hr][quote][b]Sean Lange (5/1/2014)[/b][hr]The first and the biggest issue is this is wide open to sql injection.[/quote]In most cases, I'd strongly agree with you but... with two DATE, one INT, and one CHAR(1) parameters, I'd have to say that SQL Injection is impossible for the given code.As to whether or not dynamic SQL is required for the original query or not goes, I'd have to agree with you and the others... NOT. :-)[/quote]The question is too vague and unstructured to provide anything more than a guess, so here goes:[code="sql"]IF @type &lt;&gt; '' AND @cid &lt;&gt; ''SELECT * FROM tbl WHERE [date] BETWEEN @frmdt AND @todt AND cid = @cid AND [type] = @typeIF @type &lt;&gt; ''SELECT * FROM tbl WHERE [date] BETWEEN @frmdt AND @todt AND [type] = @typeIF @cid &lt;&gt; '' SELECT * FROM tbl WHERE [date] BETWEEN @frmdt AND @todt AND cid = @cidIF @type = '' AND @cid = ''SELECT * FROM tbl WHERE [date] BETWEEN @frmdt AND @todt[/code]Wed, 07 May 2014 01:57:17 GMTChrisM@WorkRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspx[quote][b]Sean Lange (5/1/2014)[/b][hr]The first and the biggest issue is this is wide open to sql injection.[/quote]In most cases, I'd strongly agree with you but... with two DATE, one INT, and one CHAR(1) parameters, I'd have to say that SQL Injection is impossible for the given code.As to whether or not dynamic SQL is required for the original query or not goes, I'd have to agree with you and the others... NOT. :-)Tue, 06 May 2014 17:35:39 GMTJeff ModenRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxYou have three options: dynamic sql, a catch-all query, or using IF blocks to test the parameters and run whichever query fits the parameters. Catch-all queries are popular but come with a cost, which you can read about [url=http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/]here[/url]. Using IF blocks is almost always the most performant method but you then have to maintain a number of queries each differing only in the WHERE clause. Dynamic sql can certainly deal with your requirement but usually require a little more work than the other two methods. Try composing the different queries corresponding to the different parameters, something like your last post but with real column and table names, then use this as a template for building and testing your dynamic sql. Test each piece using PRINT.Tue, 06 May 2014 02:04:21 GMTChrisM@WorkRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxits not necessary to have dynamic sqli had tried with normal query but didnot work so tried iwith dynamic sqlthe out needed is display 1) date,amt with the given date range2) conditional where clause ie if @type&lt;&gt;'' then select * from tbl where date between @frmdt and @todt and type=@type if @cid&lt;&gt;'' thenselect * from tbl where date between @frmdt and @todt and cid=@cidif both not blankselect * from tbl where date between @frmdt and @todt and cid=@cid and type=@typeand both blank thenselect * from tbl where date between @frmdt and @todtSat, 03 May 2014 11:28:51 GMTssurekha2000RE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspx[quote][b]ssurekha2000 (5/1/2014)[/b][hr]i think query is unclear Transcation tbl has transcationdate, amount and cidMas_C has cid and cnameTranscation date displayed will be from & todate passed from the application1) the output needed is in all conditions transcationdate, amount if @&lt;&gt;type'' output shld be transcationdate, amount if @cid&lt;&gt;'' output shld be transcationdate, amount cname[/quote]It's unclear what you want to do. You almost certainly don't need dynamic sql. How many result sets are you expecting from this? Try to write the query(ies) [i]without [/i]using dynamic sql and post back if it doesn't work.Fri, 02 May 2014 02:10:33 GMTChrisM@WorkRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxPlease post your table structure and some sample data and what is your desired outputThu, 01 May 2014 18:59:29 GMTthavaRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxi think query is unclear Transcation tbl has transcationdate, amount and cidMas_C has cid and cnameTranscation date displayed will be from & todate passed from the application1) the output needed is in all conditions transcationdate, amount if @&lt;&gt;type'' output shld be transcationdate, amount if @cid&lt;&gt;'' output shld be transcationdate, amount cnameThu, 01 May 2014 10:58:17 GMTssurekha2000RE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxYou forgot to initialise @strqry to something other than null. Since it ultimately gets concatenated to everything, the end result is null.You've got three completely separate queries in there. What are you trying to do?How about posting what you expect to see from the PRINT statement?Thu, 01 May 2014 07:47:22 GMTChrisM@WorkRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxTwo major issues with the way you are writing this. The first and the biggest issue is this is wide open to sql injection. You should NEVER directly execute a parameter. I realize that with the datatypes of the parameters you are not at great risk currently but this approach is extremely dangerous. You can and should parameterize your dynamic sql instead of building up a string and executing it.Secondly you have the potential for some performance issues. This is a type of "catch all" query. Take a look at this post from Gail. [url=http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/]http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/[/url]She explains clearly how to deal with this type of query and properly parameterize the dynamic sql.Thu, 01 May 2014 07:40:04 GMTSean LangeRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxWhat is the result of print @str ?I think it will be empty as you are building @strqry up with a potential outcome that it will be null. When you add the to @str you will end up with a null string and therefore no query to run.The following is one way round the problem[code="sql"]@transfrmdt date,@transtodt date,@cid integer,@Type char(1)DEClare @strqry varchar(max)DEClare @str varchar(max)set @strqry= 'select name from Mas_C where 1 = 1 'If (@Type&lt;&gt;'')BEGIN SET @strqry= @strqry +' and type='''+@Type+''''ENDIf (@cname&lt;&gt;'')BEGIN SET @strqry= @strqry +' and cid='''+@cid+''''ENDSET @str =' SELECT convert(varchar (10),transdt,111)as Transdt,amtFROM Transcation WHERE 1=1and Transdt between convert(varchar (10),@transfrmdt,111) and convert(varchar (10),@transtodt,111) '+@strqryprint @strexec(@str)SELECT sum(Amt) as TotalAmtFROM Transcation WHERE Transdt between convert(varchar (10),@transfrmdt,111) and convert(varchar (10),@transtodt,111)[/code](Edited to add)I ran the query above (with @type and @cname as empty) and got the following:-[code="sql"]SELECT CONVERT(VARCHAR(10), transdt, 111) AS Transdt , amtFROM TranscationWHERE 1 = 1 AND Transdt BETWEEN CONVERT(VARCHAR(10), @transfrmdt, 111) AND CONVERT(VARCHAR(10), @transtodt, 111)SELECT nameFROM Mas_CWHERE 1 = 1[/code]I'm not sure if you wanted two separate queries, or if you wanted to have the second as a filter for name.Thu, 01 May 2014 03:30:18 GMTStuart DaviesRE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxswap what?i am not getting any resultsThu, 01 May 2014 03:20:58 GMTssurekha2000RE: forming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspx[quote][b]ssurekha2000 (5/1/2014)[/b][hr]have a sp with 4 parameters the values of this parameters is obtained from applicationcurrently i have@transfrmdt date, @transtodt date, @cid integer, @Type char(1)DEClare @strqry varchar(max) DEClare @str varchar(max) If (@Type&lt;&gt;'') BEGIN SET @strqry= @strqry +' and type='''+@Type+'''' END If (@cname&lt;&gt;'') BEGIN SET @strqry= @strqry +'select name from Mas_C where cid='''+@cid+'''' END SET @str =' SELECT convert(varchar (10),transdt,111)as Transdt,amt FROM Transcation WHERE 1=1and Transdt between convert(varchar (10),@transfrmdt,111) and convert(varchar (10),@transtodt,111) ' +@strqryprint @strexec(@str)SELECT sum(Amt) as TotalAmtFROM Transcation WHERE Transdt between convert(varchar (10),@transfrmdt,111) and convert(varchar (10),@transtodt,111)i am not getting the result[/quote]I take it that print @str does not give you the query you are looking for. I suspect that you need to look at the order in which you are building up the string. Initially you SET @strqry= @strqry +' and type='''+@Type+'''' then you set it to 'select name from Mas_C where cid='''+@cid+''''From what I can see you need to swap the order of these, also it might help to set a value for @strqry [b]then[/b] add any "where " filters later.Thu, 01 May 2014 03:11:40 GMTStuart Daviesforming a dynamic queryhttp://www.sqlservercentral.com/Forums/Topic1566653-392-1.aspxhave a sp with 4 parameters the values of this parameters is obtained from applicationcurrently i have@transfrmdt date, @transtodt date, @cid integer, @Type char(1)DEClare @strqry varchar(max) DEClare @str varchar(max) If (@Type&lt;&gt;'') BEGIN SET @strqry= @strqry +' and type='''+@Type+'''' END If (@cname&lt;&gt;'') BEGIN SET @strqry= @strqry +'select name from Mas_C where cid='''+@cid+'''' END SET @str =' SELECT convert(varchar (10),transdt,111)as Transdt,amt FROM Transcation WHERE 1=1and Transdt between convert(varchar (10),@transfrmdt,111) and convert(varchar (10),@transtodt,111) ' +@strqryprint @strexec(@str)SELECT sum(Amt) as TotalAmtFROM Transcation WHERE Transdt between convert(varchar (10),@transfrmdt,111) and convert(varchar (10),@transtodt,111)i am not getting the resultThu, 01 May 2014 02:38:54 GMTssurekha2000