通过SQL Server创建视图

时间:2014-08-31 02:33:03

标签: sql sql-server tsql

USE PayCalculator; 
CREATE VIEW PayCalculator.Pay 
AS
    SELECT
       PayStructure.WeekIncluded AS PaidWeeks, 
       PayStructure.PayDate AS PayDate, 
       dbo.PayStructure.PayYear AS PayYear, 
       Months.PMonth 
    FROM 
       PayStructure,Months
    INNER JOIN 
       Months.PMonth ON PayStructure.MonthID = PayCalculator.dbo.Months.PMonths

似乎连接的视图不会创建。我很困惑为什么,因为它在语法上似乎是正确的。

我得到的错误:

  

Msg 208,Level 16,State 1,Procedure Pay,Line 5   无效的对象名称'Months.PMonth'。

但是,数据库中所有列出的列都是正确的

dbo.Months

Months Table

dbo.PayStructure

PayStructure Tablee

即使使用:

USE PayCalculator;
GO

SELECT 
    PayStructure.WeeksIncluded, PayStructure.PayDate, PayStructure.PayYear
FROM 
    PayStructure AS sd
JOIN 
    AnualMonths.PMonths AS p ON sd.MonthID = AnualMonths.PMonths 
GO

2 个答案:

答案 0 :(得分:2)

您的语法非常混乱,您使用的是旧的连接语法(FROM PayStructure, Months)以及普通的连接语法(JOIN ON...) - 您还尝试直接连接到< strong>列而不是表格(即您尝试INNER JOIN Months.PMonth而不是INNER JOIN Months

FROM PayStructure, Months
INNER JOIN Months.PMonth ON PayStructure.MonthID = PayCalculator.dbo.Months.PMonths

根据我的想法,尝试下面的脚本:

USE PayCalculator; 
CREATE VIEW PayCalculator.Pay 
AS

SELECT ps.WeekIncluded as PaidWeeks,
       ps.PayDate as PayDate,
       ps.PayYear as PayYear,
       months.PMonth
FROM dbo.PayStructure ps
JOIN dbo.Months months on ps.MonthId = months.ID

答案 1 :(得分:1)

连接列的数据类型应该相同:

CREATE VIEW PayCalculator.Pay 
AS

SELECT ps.WeekIncluded as PaidWeeks,
       ps.PayDate as PayDate,
       ps.PayYear as PayYear,
       months.PMonth
FROM dbo.PayStructure ps
JOIN dbo.Months months on ps.MonthId = months.ID