动态表名称的SQL变量随获取日期而变化

时间:2017-04-05 12:03:27

标签: sql sql-server

我有以下sql,我无法正常工作,每天都会创建一个表格,每天以表格名称末尾的YYYYMMDD格式创建。 这是SQL:

    DECLARE @var INT



    SET @var = CAST(CONVERT(NVARCHAR(8),GETDATE()-1,112) AS int)

    SELECT @VAR


    SELECT
    CASE WHEN LEN("AssociatedData") = 0 OR "AssociatedData" IS NULL THEN '*Unknown*' ELSE AssociatedData END AS AssociatedData,
    "CallEvent",
    CASE WHEN LEN("CallEventName") = 0 OR "CallEventName" IS NULL THEN '*Unknown*' ELSE CallEventName END AS CallEventName,
    "CallID",
    CASE WHEN LEN("Destination") = 0 OR "Destination" IS NULL THEN '*Unknown*' ELSE Destination END AS Destination,
    CASE WHEN LEN("EventData") = 0 OR "EventData" IS NULL THEN '*Unknown*' ELSE EventData END AS EventData,
    "FirstEventTimestamp",
    "SequenceNumber",
    "Source",
    CASE WHEN LEN("TelsetLoginID") = 0 OR "TelsetLoginID" IS NULL THEN '*Unknown*' ELSE TelsetLoginID END AS TelsetLoginID,
    "Time",
    "Timestamp"
    FROM concat(eCallByCallStat,@var)

我需要将其作为SQL查询而不是StoredProcedure。

这是否可以在表名之后直接附加日期键。

谢谢

1 个答案:

答案 0 :(得分:0)

DECLARE @tsql VARCHAR(MAX)
DECLARE @var DATE = GETDATE() - 1

SET @tsql = '
SELECT
  [AssociatedData] = CASE WHEN LEN( [AssociatedData] ) > 0 THEN [AssociatedData] ELSE ''*Unknown*'' END,
  [CallEvent],
  [CallEventName] = CASE WHEN LEN( [CallEventName] ) > 0 THEN [CallEventName] ELSE ''*Unknown*'' END,
  [CallID],
  [Destination] = CASE WHEN LEN( [Destination] ) > 0 THEN [Destination] ELSE ''*Unknown*'' END,
  [EventData] = CASE WHEN LEN( [EventData] ) > 0 THEN [EventData] ELSE ''*Unknown*'' END,
  [FirstEventTimestamp],
  [SequenceNumber],
  [Source],
  [TelsetLoginID] = CASE WHEN LEN( [TelsetLoginID] ) > 0 THEN [TelsetLoginID] ELSE ''*Unknown*'' END,
  [Time],
  [Timestamp]
FROM 
  ' + CONCAT( 'eCallByCallStat', CONVERT( VARCHAR, @var, 112 ) )

PRINT @tsql
EXEC sp_executesql @tsql