I want to use some dynamic SELECT
statements. The name of the table or column could be different, that's why I use dynamic stored procedures like this:
CREATE PROCEDURE [dbo].[test_sp](
@database nvarchar(70)= ''
, @table_name nvarchar(70)= ''
, @column nvarchar(70)= ''
)
AS
DECLARE @sql nvarchar(max)= 'SELECT ' + @column +
'FROM [' + @database +
'].[dbo].[' + @table_name + '] '
EXEC(@sql);
GO
This works very well. Now I got more and more store procedure with similar code snippets. Concerning the maintenance I want to reuse the snippets or use dynamic functions.
An example: I have another stored procedure which should "filter" the result set of this presented example (an additional requirement is not to add a parameter to filter this result set directly)
If this SQL would be static i would use a function. In my cases I need that dynamic. UDF doesn't allow that "EXEC"-stuff and the result set of stored procedures aren't reusable.
I would expect that many people got the problem like me. I googled a lot and tried several things, but nothing works...
I need a way to reuse stored procedure code snippets or reuse the result set of a store procedure or a function that is dynamic like a stored procedure.
So can anybody help me and give me another idea?
Thanks for your help or solution ideas :)
V
Edit/Solution:
First of all everybody should read the comment of "Joel Coehoorn" and " Panagiotis Kanavos". They are absolutely right and this code snippets aren't recommended in a web application or something like this. In my special case it's a local application and injections and other security aspects aren't relevant.
After that I have to thank you "Abdul Rehman Sayed". The following solution based on his idea.
To realize that requirement in SQL you have to create two stored procedures. The first on is create a result set and write it into a temporary table.
The second one execute the first stored procedure, filter the result and drop the temporary table.
First one:
ALTER PROCEDURE [dbo].[test_SP_FXN](
@database nvarchar(70)= ''
) AS
DECLARE @create nvarchar(max)= '
CREATE TABLE ['+@database+'].[dbo].[temp_result](
[name] [nvarchar](150) NULL
,[id] [nvarchar](150) NULL
,[desc] [nvarchar](450) NULL ) ';
DECLARE @sql nvarchar(max)= '
INSERT INTO ['+@database+'].[dbo].[temp_result]
SELECT TOP 1000 name, id, desc
FROM ['+@database+'].[dbo].[important_table] ';
EXEC(@create);
EXEC(@sql);
The second one:
ALTER PROCEDURE [dbo].[test_SP_2](
@database nvarchar(70)= ''
) AS
-- create the temp table with the result of the store procedure
EXEC ('['+@database+'].[dbo].[test_SP_FXN] '+@database )
-- Execute the real sql
DECLARE @sql nvarchar(max)= 'select * FROM ['+@database+'].[dbo].[temp_result] WHERE ID > 5'
EXEC(@sql);
-- drop the temp table because there is no use any more
EXEC ('DROP TABLE ['+@database+'].[dbo].[temp_result] ')
This is only an example but i think the principle will be clear.
Thanks for your help and comments.