在视图中使用临时表

时间:2010-04-26 03:45:13

标签: sql sql-server

我真的想创建一个视图。

我知道你不能在MSSQL2005视图中使用临时表。没有重写sql,有什么明显的我错过了吗?

备份计划是使用存储过程。

干杯

select * into #temp from vwIncidents 

SELECT     vwIncidents.incidentcode, employeecode, EMPOS.POS_L4_CDA as areaAtTimeOfIncident
into #temp1
FROM         vwIncidents 
INNER JOIN EMPOS ON vwIncidents.employeecode = EMPOS.DET_NUMBERA 
WHERE    EMPOS.POS_STARTC <  vwIncidents.incidentdate
AND      (EMPOS.POS_ENDD > vwIncidents.incidentdate OR EMPOS.POS_ENDD IS NULL)
order by incidentcode

select #temp.*, #temp1.areaAtTimeOfIncident from #temp
left outer join #temp1 on #temp.incidentcode = #temp1.incidentcode 
and #temp.employeecode = #temp1.employeecode
order by incidentcode

3 个答案:

答案 0 :(得分:7)

您可以使用CTE:

WITH cteIncidents (incidentcode, employeecode, areaAtTimeOfIncident)
AS
(
SELECT 
    vwIncidents.incidentcode, employeecode, EMPOS.POS_L4_CDA as areaAtTimeOfIncident 
FROM
    vwIncidents  
INNER JOIN EMPOS ON vwIncidents.employeecode = EMPOS.DET_NUMBERA  
WHERE    EMPOS.POS_STARTC <  vwIncidents.incidentdate 
AND      (EMPOS.POS_ENDD > vwIncidents.incidentdate OR EMPOS.POS_ENDD IS NULL) 
)

SELECT 
    incidentcode, employeecode, areaAtTimeOfIncident
FROM 
    cteIncidents 
left outer join vwIncidents on vwIncidents.incidentcode = cteIncidents.incidentcode  
and vwIncidents.employeecode = cteIncidents.employeecode 
ORDER BY
    incidentcode 

(可能需要将连接更改为右侧,但您明白了......)

答案 1 :(得分:3)

你试过在不使用临时表的情况下重写这个吗?

这样的东西
select  temp.*, 
        temp1.areaAtTimeOfIncident 
from    (
            select * 
            from vwIncidents
        ) temp  left outer join 
        (
            SELECT  vwIncidents.incidentcode, 
                    employeecode, 
                    EMPOS.POS_L4_CDA as areaAtTimeOfIncident 
            FROM    vwIncidents  INNER JOIN 
                    EMPOS   ON vwIncidents.employeecode = EMPOS.DET_NUMBERA  
            WHERE   EMPOS.POS_STARTC <  vwIncidents.incidentdate 
            AND     (   
                        EMPOS.POS_ENDD > vwIncidents.incidentdate 
                        OR EMPOS.POS_ENDD IS NULL
                    )
        ) temp1     on  temp.incidentcode = temp1.incidentcode  
                and temp.employeecode = temp1.employeecode 
order by incidentcode 

答案 2 :(得分:0)

使用WITH声明。