如何通过 SQL 将计算列添加到 Access

How to add a calculated column to Access via SQL

如何将计算列添加到 SQL 中的 Access table?

我知道我可以添加一个带有 SQL 的列,如下所示:

ALTER TABLE Clients ADD COLUMN AccountDate TEXT(60)

谢谢, 维托

你想让它计算什么?您是否尝试过类似的东西:

ALTER TABLE Clients 
ADD COLUMN AccountDate AS (Column1 * Column2);

我认为 MS Access 不支持计算列。相反,您可以创建一个视图:

create view v_clients as
    select c.*, (col1 + col2) as col3
    from clients;

您不能使用 SQL 添加计算列,因为计算字段需要表达式,而不能通过 SQL 提供。从技术上讲,计算字段是一种基本类型 - int、double、text 等。基本类型之上是帮助 Access 执行 math/logic.

的表达式

您可以使用 VBA 创建计算列

-- create a module and let's assume that
-- your table has Field1 integer and Field2 integer
-- we will add field3

Public Sub CreateField()

    Dim DB As DAO.Database
    Dim TableDef As DAO.TableDef
    Dim Fld As DAO.Field2

    Set DB = CurrentDb()
    Set TableDef = DB.TableDefs("Table1")

    Set Fld = TableDef.CreateField("field3", dbDouble)
    Fld.Expression = "[field1] * [field2]"
    TableDef.Fields.Append Fld

    MsgBox "Added"

End Sub

正如 Gordon 和 BJones 提到的,您可以使用相关计算创建视图或保存查询。