无法使用临时表创建视图

时间:2017-08-22 14:27:15

标签: sql-server tsql

希望你能提供帮助。

我意识到你不能在SQL视图中拥有Temp表,所以在下面转换查询的最佳方法是什么,以便它可以在SQL视图中使用。

提前致谢

abort()

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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'

答案 2 :(得分:1)

使用CTE

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'