在单独的表上创建计算列?

时间:2016-03-03 10:32:37

标签: sql sql-server sql-server-2008 view calculated-columns

我在TEventTEmployee表上创建了2个计算列,并在这些计算列上使用Index,没有任何问题。另一方面,由于在数据操作过程中遇到了某些问题,我们需要使用除这些之外的其他表。此时,我想知道可以通过在TEventTEmployee表之外的单独表上创建它们来使用这些计算列吗?除此之外,使用View代替Computed Column更好吗?能否请您澄清这两种方法?

--Creating Computed Columns:
ALTER TABLE TEvent ADD CardNoRightEight AS RIGHT(CAST(CardNo AS int), 8) 
ALTER TABLE TEmployee ADD CardNoRightEight AS RIGHT(CAST(CardNo AS int), 8) 

--Creating Index
CREATE INDEX TEmployee_CardNoRightEight_IDX ON TEmployee (CardNoRightEight)
CREATE INDEX TEvent_CardNoRightEight_IDX ON TEvent (CardNoRightEight)


更新:这是我的SELECT查询,包含Join和CTE(公用表表达式)

;WITH a AS (
    SELECT emp.EmployeeName, emp.Status, dep.DeptName, job.JobName, emp.CardNoRightEight
    FROM TEmployee emp
    LEFT JOIN TDeptA AS dep ON emp.DeptAID = dep.DeptID
    LEFT JOIN TJob AS job ON emp.JobID = job.JobID
    ),
    b AS (
    SELECT eve.EventID, eve.EventTime, evt.EventCH, dor.DoorName, eve.CardNoRightEight
    FROM TEvent eve
    LEFT JOIN TEventType AS evt ON eve.EventType = evt.EventID
    LEFT JOIN TDoor AS dor ON eve.DoorID = dor.DoorID)

SELECT * FROM b LEFT JOIN a ON a.CardNoRightEight = b.CardNoRightEight
ORDER BY b.EventID ASC

1 个答案:

答案 0 :(得分:0)

你实际上可以双管齐下。

第一种方法:创建用户定义的函数

CREATE FUNCTION dbo.TEvent(@Column1_Val INT)
RETURNS INT
AS
  BEGIN
      RETURN
        (--SQL Logic)
  END

您可以进一步使用此用户定义的函数将列添加到不同的表中,如下所示:

ALTER TABLE dbo.TEvent_CardNoRightEight_IDX 
ADD CardNoRightEight AS dbo.TEvent(Column1)

但我个人建议使用观点。