2017-04-05 79 views
0

我有以下的SQL,我不能工作,有一個表,它每天創建與YYYYMMDD格式在表名每天結束。 這裏是SQL: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的。

這是否可能在表名後直接附加datekey。

謝謝

+1

不,這是不可能的。您需要使用動態SQL。或者,將創建表的作業更改爲*將這些行插入到主表中。 –

+0

SQL中的動態SQL如何表示感謝? – abs786123

+1

以下是[Microsoft動態SQL文檔文檔](https://docs.microsoft.com/zh-cn/sql/odbc/reference/dynamic-sql)的鏈接。每天創建一個新表會使查詢寫入變得複雜。您是否考慮過將日期列添加到固定的表名中? –

回答

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 
+0

謝謝,但我收到此消息消息214,級別16,狀態2,過程sp_executesql,行1 過程期望類型爲'ntext/nchar/nvarchar'的參數'@statement'。 – abs786123