ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Tip Pass table name dynamically to SQL Server query or stored procedure
Author Name: Mudassar Khan Published Date: May 13, 2009
Filed Under :
SQL Server
Views: 2594

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'





If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

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.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code