2010-04-26 39 views
5

Tôi thực sự muốn tạo chế độ xem.Sử dụng bảng tạm thời trong chế độ xem

Tôi biết bạn không thể sử dụng bảng tạm thời trong chế độ xem MSSQL2005. Nếu không viết lại sql, có bất cứ điều gì rõ ràng tôi đã bỏ qua?

Kế hoạch dự phòng là sử dụng proc được lưu trữ.

Cheers

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

Tôi khá chắc chắn rằng bạn có thể thả đầu tiên ORDER BY ... –

Trả lời

3

hav bạn đã cố gắng viết lại này mà không có việc sử dụng bảng tạm thời?

Something như

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

cảm ơn tuyệt vời .. –

0

Sử dụng các tuyên bố WITH.

7

Bạn có thể sử dụng một 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 

(Có thể cần phải thay đổi để tham gia một quyền, nhưng bạn sẽ có được ý tưởng ...)

+0

rất thú vị ... sẽ xem xét điều này quá ... người xem đánh bại bạn bằng một vài phút :-) –

Các vấn đề liên quan