How to add a calculated column to Access via SQL

本小妞迷上赌 提交于 2019-12-31 01:45:11

问题


How do i add a calculated column to an Access table in SQL?

I know i can add a column with SQL like this:

ALTER TABLE Clients ADD COLUMN AccountDate TEXT(60)

Thanks, Vítor


回答1:


You cannot add a calculated column with SQL because calculated field requires an expression and that cannot be supplied through SQL. Technically, a calculated field is a base type - int, double, text etc. Above the base type is an expression that helps Access do the math/logic.

You could use VBA to create a calculated column

-- 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

As Gordon and BJones mentioned, you could create a view or saved query with relevant calculation.




回答2:


I don't think MS Access supports computed columns. Instead, you can create a view:

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



回答3:


What do you want it to calculate? Have you tried something like:

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


来源:https://stackoverflow.com/questions/31621363/how-to-add-a-calculated-column-to-access-via-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!