2017-08-22 53 views
2

希望你能提供幫助。無法使用臨時表創建視圖

我意識到你不能在SQL視圖中有臨時表,所以什麼是最好的方式來轉換下面的查詢,以便它可以在SQL視圖中使用。

在此先感謝

SELECT 
    a.KeyField, a.AlphaValue AS Compostable 
INTO 
    #DAT 
FROM 
    [SysproCompanyA].[dbo].AdmFormData a 
WHERE 
    a.FieldName = 'DAT001' 

SELECT 
    b.KeyField, b.AlphaValue AS Trial 
INTO 
    #PAS 
FROM 
    [SysproCompanyA].[dbo].AdmFormData b 
WHERE 
    b.FieldName = 'PAS001' 

SELECT 
    c.KeyField AS JobNumber, c.Compostable, d.Trial 
FROM 
    #DAT c 
INNER JOIN 
    #PAS d ON c.KeyField = d.KeyField 
WHERE 
    c.KeyField = '00170579' 

DROP TABLE #DAT 
DROP TABLE #PAS 
+0

查找CTE,公用表表達式。 – OTTA

回答

3

使用CTE的

WITH [DAT] as (
    SELECT a.KeyField, a.AlphaValue AS Compostable 
    FROM [SysproCompanyA].[dbo].AdmFormData a 
    WHERE a.FieldName = 'DAT001' 
), [PAS] as (
    SELECT b.KeyField, b.AlphaValue AS Trial 
    FROM [SysproCompanyA].[dbo].AdmFormData b 
    WHERE b.FieldName = 'PAS001' 
) 
SELECT c.KeyField AS JobNumber, c.Compostable, d.Trial 
FROM [DAT] c 
INNER JOIN [PAS] d ON c.KeyField = d.KeyField 
WHERE c.KeyField = '00170579' 
1

使用熱膨脹係數

create view MyView 
as 
with DAT as 
(
    SELECT a.KeyField, a.AlphaValue AS Compostable 
    FROM [SysproCompanyA].[dbo].AdmFormData a 
    WHERE a.FieldName = 'DAT001' 
) 
, PAS as 
( 
    SELECT b.KeyField, b.AlphaValue AS Trial 
    FROM [SysproCompanyA].[dbo].AdmFormData b 
    WHERE b.FieldName = 'PAS001' 
) 
    SELECT c.KeyField AS JobNumber, c.Compostable, d.Trial 
    FROM DAT c INNER JOIN PAS d ON c.KeyField = d.KeyField 
    WHERE c.KeyField = '00170579' 
7

也許我們就可以一起加入這兩個表,有相同的限制,然後選擇所需的列:

SELECT 
    c.KeyField AS JobNumber, 
    c.Compostable, 
    d.Trial 
FROM [SysproCompanyA].[dbo].AdmFormData c 
INNER JOIN [SysproCompanyA].[dbo].AdmFormData d 
    ON c.KeyField = d.KeyField 
WHERE 
    c.FieldName = 'DAT001' AND 
    d.FieldName = 'PAS001' AND 
    c.KeyField = '00170579' 
+0

你的回答比較好。我只是回答這個問題。你解決了這個問題;) –

+0

@JuanCarlosOropeza不,你是對的謹慎,並儘量堅持儘可能的原始查詢。對於另一個問題,一個簡單的連接可能不會取代OP所擁有的。 –