ASP Snippets

Categories






Alerts

Free Alerts

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




Follow us on twitter.




Zoom In | Zoom Out


Author is awarded Most Valuable Professional award by Microsoft ASP/ASP.Net

Tip – Pass table name dynamically to SQL Server query or stored procedure

Author:Mudassar Khan

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'




Posted: May 13 2009, 03:50 by Mudassar Khan | Comments (2) RSS comment feed |
Filed under: SQL Server | Tips

Views: 2517
Page copy protected against web site content infringement by Copyscape


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share





Comments









Community News





Web Hosting SpotLight


Consulting


For consulting and work related queries click here.



Advertise


Advertise with us. For more details click here.


Suggestions


Please provide your valuable suggesstions here.

This Site is hosted on

Lunarpages.com Web Hosting