Wednesday 19 January 2011

Execute a generic query on sql server.

Question:
Execute a generic query string on sql server.




Answer:
Sometimes it is impossible to use a standard stored procedure to get what you want.
In thoses cases you have to create the query inside the procedure itself and execute the query.

Here is an example :
ALTER PROCEDURE [dbo].[Get_Results] 
   @WhereClause nvarchar(max) = '',
   @TableName nvarchar(255)
AS
BEGIN

   DECLARE @SqlCmd as nvarchar(max)
   if(RTRIM(@Selection) = '')
   begin 
      set @SqlCmd =  'SELECT * FROM ' + @TableName 
   end
   else
   begin
      set @SqlCmd =  'SELECT * FROM ' + @TableName + ' WHERE ' + @WhereClause 
   end
 
   --PRINT @SqlCmd;
   EXEC(@SqlCmd);
    
END

No comments: