I have worked on SQL stored procedures and I have noticed that many people use two different approaches –
First, to use select queries i.e. something like
Select * from TableA where colA = 10 order by colA
Second, is to do the same by constructing a query i.e. like
Declare @sqlstring varchar(100)
Declare @sqlwhereclause varchar(100)
Declare @sqlorderby varchar(100)
Set @sqlstring = 'Select * from TableA '
Set @sqlwhereclause = 'where colA = 10 '
Set @sqlorderby = 'order by colA'
Set @sqlstring = @sqlstring + @sqlwhereclause + @sqlorderby
exec @sqlstring
Now, I know both work fine. But, the second method I mentioned is a little annoying to maintain.
I want to know which one is better? Is there any specific reason one would resort to one method over the other? Any benefits of one method over other?
Use the first one. This will allow a query plan to be cached properly, apart from being the way you are supposed to work with SQL.
The second one is open to SQL Injection attacks, apart from the other issues.
With the dynamic SQL you will not get compile time checking, so it may fail only when invoked (the sooner you know about incorrect syntax, the better).
And, you noted yourself, the maintenance burden is also higher.