如何在视图中添加单个字段

时间:2013-11-18 08:59:43

标签: mysql asp.net sql sql-server

我正在尝试在MS SQL中创建一个具有两个表和单个字段的连接的视图。 我已经完成了连接部分,但现在我想在此视图中添加一个新字段,该字段不在任何已连接的表中。 所以任何人都知道如何在视图中创建这个新领域。

2 个答案:

答案 0 :(得分:0)

如果需要,您可以显式命名每个字段,并根据需要使用AS对其进行别名。例如:

SELECT si.field1 as si_field1,
       si.field2 as si_field2,
       ind_data.field1 as ind_data_field1
  FROM sites_indexed as si
  LEFT JOIN individual_data as ind_data 
         ON si.id = ind_data.site_id 

然后您可以在结果集中引用别名。

答案 1 :(得分:0)

如果您想要ACTIVE字段中所有行的默认值,请尝试使用

CREATE VIEW Slots AS 
SELECT Event.EventId, 
Event.eventName, 
examCenter.centerId, 
examCenter.centerName, 
slotTime.slotTimeId, 
slotTime.FromTime, 
slotTime.ToTime, 
slotTime.Dated, 
examCenter.noOfSeats,
CAST(1 AS bit) AS Active 
FROM examCenter 
INNER JOIN Event 
ON examCenter.eventId = Event.EventId 
INNER JOIN slotTime ON Event.EventId = slotTime.eventId

如果ACTIVE字段的值取决于某些条件,请说

slottime.Dated => getdate()

然后,你需要替换

CAST(1 AS bit) AS Active

在上面的代码中,带

CAST(CASE WHEN slottime.Dated => getdate() THEN 1 ELSE 0 AS bit) AS ACTIVE