您好我试图每天用新表更新MASTER TABLE, 表名不同,每日例[Collections_LT5_PH7_20160117],[Collections_LT5_PH7_20160118]等。 到目前为止,这是我的更新查询。
INSERT INTO [Collections_LT5_PH7_Master]
(
Date_ID,
Record_Num,
SITE_ID,
ACCT_NUM,
PHONE_NUM,
Dial_Count,
Call1_Phone,
Call1_dt,
Disp1_Id,
Call2_Phone,
Call2_dt,
Disp2_Id,
Phone1TimeZoneId
)
SELECT
CONVERT(VARCHAR, DATEADD(dd, -1, GETDATE()), 112) as Data_ID,
Record_Num,
SITE_ID,
ACCT_NUM,
PHONE_NUM,
Dial_Count,
Call1_Phone,
Call1_dt,
Disp1_Id,
Call2_Phone,
Call2_dt,
Disp2_Id,
Phone1TimeZoneId,
FROM [Collections_LT5_PH7_20160118]
我想更新,而不必手动更改数据从前一天拉出的表中的日期。我试过了
FROM '[Collections_LT5_PH7_'+CONVERT(VARCHAR, DATEADD(dd, -1, GETDATE()), 112)+']'
但它出错了。
任何想法?
答案 0 :(得分:1)
你几乎就在那里
尝试这个曾经对查询感到满意,取消执行部分:
DECLARE @SQL VARCHAR(MAX) = 'INSERT INTO [Collections_LT5_PH7_Master]
(
Date_ID,
Record_Num,
SITE_ID,
ACCT_NUM,
PHONE_NUM,
Dial_Count,
Call1_Phone,
Call1_dt,
Disp1_Id,
Call2_Phone,
Call2_dt,
Disp2_Id,
Phone1TimeZoneId
)
SELECT
CONVERT(VARCHAR, DATEADD(dd, -1, GETDATE()), 112) as Data_ID,
Record_Num,
SITE_ID,
ACCT_NUM,
PHONE_NUM,
Dial_Count,
Call1_Phone,
Call1_dt,
Disp1_Id,
Call2_Phone,
Call2_dt,
Disp2_Id,
Phone1TimeZoneId
FROM [Collections_LT5_PH7_'+CONVERT(VARCHAR, DATEADD(dd, -1, GETDATE()), 112)+']'
PRINT (@SQL)
--EXECUTE (@SQL);
答案 1 :(得分:0)
您不能动态地将表名设置为SQL查询,我猜这是一个安全功能。
您可以使用预准备语句和“EXECUTE”命令来解决它。以下在MySQL中工作,显然你需要修改查询字符串和填充的表名到你想要的那个。
set @tablename := 'test';
set @q := 'select * from ';
select concat(@q,@tablename) into @s;
prepare stmt from @s;
execute stmt;