SQL Stored procedure with variable table name

Sql

Public Domain

Download (right click, save as, rename as appropriate)

Embed

Tags:

sql
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Expressions_FetchPeriodRawData]
	@objectId int,
	@objectPropertyId int,
	@startDate date,
	@endDate date,
	@tableName nvarchar(255)
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @actualTableName AS nvarchar(255)
    SELECT @actualTableName = QUOTENAME(TABLE_NAME)
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME = @tableName

    DECLARE @sql AS NVARCHAR(MAX)
    SELECT @sql = '
	SELECT TOP 1
			T.ObjectId as ObjectId,
            T.ObjectPropertyId as ObjectPropertyId,
            DateReported as DateReported,
            Value as Value
    FROM   ' + @actualTableName + ' T
    WHERE   T.ObjectPropertyId = @objectPropertyId
			AND T.ObjectId = @objectId
			T.DateReported BETWEEN @startDate AND @endDate
    ORDER BY T.DateReported DESC'
             
	EXEC sp_executesql @sql, 
N'	@objectId int,
	@objectPropertyId int,
	@startDate date,
	@endDate date',
	@objectId,
	@objectPropertyId,
	@startDate,
	@endDate;
END