Pages

Tuesday 26 February 2013

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

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'
 

No comments:

Post a Comment