Does anyone know of a way to append text to a stored procedure from within another stored procedure? I would like to do something like the following in SQL Server 2005:
Declare str as Nvarchar(Max) = ''
set @spStr = dbo.spTest + 'Where testCol1 = ''Test'''
exec(@spStr)
I understand this may open some discussion about SQL injection attacks. I’m simply looking to see if syntax exsists to extend a stored procedure by passing it a where clause dynamically in the above manner.
There are some options.
You can alter the actual SP using the metadata in INFORMATION_SCHEMA.ROUTINES (not really what I think you are wanting to be doing)
You can parameterize the SP – this should not be vulnerable to injection if the SP uses the variable directly and not to dynamically make SQL.
You might consider using a view or an inline or multi-step table-valued function instead, which can be used like a parameterized view (inline being more efficient) –
SELECT * FROM udf_Test WHERE TestCol1 = 'Test'.You can take the results of the SP and put them in a temporary table or table variable and query against that.