Friday 12 February 2016

how to pass Table name as Parameter to Stord Procedure in SqlServer



Description:-

In this example we explain that how to pass Table name as Parameter to Stord Procedure in SqlServer.or how to pass Table name as a parameter or variable to sp_executesql command in SQLServer.

Sometime we have requirement like to pass only Table name to stored procedure as a parameter and returns the record from it depend on pass the Table argument.

Suppose if you pass the Employee as the Table name parameter then procedure will returns the Employees record same like for other table that you want to pass to stored procedure as a parameter.
So how to pass Table as a parameter to the stored procedure in SQLServer.



Procedure:-

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE SP_DyanmicTable
      @TableName SYSNAME
AS
BEGIN
      SET NOCOUNT ON;
      DECLARE @DynamicQuery NVARCHAR(4000)
      SET @DynamicQuery = N'SELECT * FROM ' + @TableName
      EXECUTE sp_executesql @DynamicQuery
END
GO

 How To Call :-


EXEC SP_DyanmicTable 'LeadBase'

0 comments:

Post a Comment