SQL为此Query创建临时表

时间:2013-07-03 18:45:27

标签: sql tsql sql-server-2012 ssms

我想创建一个临时表来存储此查询,以便我可以更新另一个表。

SELECT SaginawUtilityData.ServiceFrom, SaginawUtilityData.ServiceThru, 

BillingMonth = dbo.fn_MonthWithMostDaysInRange(ServiceFrom, ServiceThru),

SaginawUtilityData.Usage, SaginawUtilityData.UtilityCharges

FROM SaginawUtilityData

JOIN tblMEP_CustomerAccounts
ON SaginawUtilityData.AccountNumber = tblMEP_CustomerAccounts.AccountNumber

JOIN tblMEP_Customers
ON tblMEP_CustomerAccounts.CustomerID = tblMEP_Customers.ID

JOIN tblMEP_UtilityCompanies
ON tblMEP_UtilityCompanies.ID = tblMEP_CustomerAccounts.UtilityCompanyID

JOIN tblMEP_Meters
ON tblMEP_CustomerAccounts.ID = tblMEP_Meters.CustomerAccountID
WHERE tblMEP_Customers.ID = 43

如果您可以进行更新,那就太棒了:这是另一个表格,我希望从上表中插入到这一列中的列:

SELECT tblMEP_MonthlyDATA.CycleStartDate, tblMEP_MonthlyDATA.CycleEndDate, 

tblMEP_MonthlyDATA.BillingMonth, tblMEP_MonthlyDATA.Consumption,

tblMEP_MonthlyDATA.Charge

FROM tblMEP_MonthlyData

感谢。

1 个答案:

答案 0 :(得分:1)

我不确定我是否真的理解你在问什么,但我想你问的是如何将顶部查询中的数据直接放入底部查询中显示的表列中,所以:

INSERT tblMEP_MonthlyDATA (
    CycleStartDate, CycleEndDate, BillingMonth, Consumption, Charge)
SELECT 
    SaginawUtilityData.ServiceFrom, 
    SaginawUtilityData.ServiceThru, 
    dbo.fn_MonthWithMostDaysInRange(ServiceFrom, ServiceThru),
    SaginawUtilityData.Usage, 
    SaginawUtilityData.UtilityCharges
FROM SaginawUtilityData
    JOIN tblMEP_CustomerAccounts ON SaginawUtilityData.AccountNumber = 
                                           tblMEP_CustomerAccounts.AccountNumber
    JOIN tblMEP_Customers ON tblMEP_CustomerAccounts.CustomerID = tblMEP_Customers.ID
    JOIN tblMEP_UtilityCompanies ON tblMEP_UtilityCompanies.ID = 
                                           tblMEP_CustomerAccounts.UtilityCompanyID
    JOIN tblMEP_Meters ON tblMEP_CustomerAccounts.ID = tblMEP_Meters.CustomerAccountID
WHERE 
    tblMEP_Customers.ID = 43 --or other set of conditions

希望这会有所帮助(或者至少与你想知道的内容有关)