Tip Pass table name dynamically to SQL Server query or stored procedure
 
Author:
Filed Under: SQL Server
Published Date: May 13, 2009
Views: 4540
 

Abstract: Here Mudassar Ahmed Khan has explained how to dynamically pass table name to SQL Query or Stored Procedure in SQL Server 2000 2005 2008

Comments:  0

 

This is another tip in SQL Server that I decided to share is how to pass table name dynamically to a query or stored procedure.

Means the same query can be used on multiple tables if they have same structure.

 

DECLARE @Table_Name sysname, @DynamicSQL nvarchar(4000)

SET @Table_Name = 'Employees'

SET @DynamicSQL = N'SELECT * FROM ' + @Table_Name

EXECUTE sp_executesql @DynamicSQL

 

The above query is dynamically build and executed on the table based on the table name that is passed.

 

If you need to do the above with a stored procedure you can do in the following way

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE PROCEDURE Dynamic_SP

      @Table_Name sysname

AS

BEGIN

      SET NOCOUNT ON;

      DECLARE @DynamicSQL nvarchar(4000)

      SET @DynamicSQL = N'SELECT * FROM ' + @Table_Name

      EXECUTE sp_executesql @DynamicSQL

END

GO

 

And to execute the stored procedure

EXEC Dynamic_SP 'Employees'












Related Articles



Comments

No comments have been added to this article.

Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit