MS SQL 服务器 - 添加带子查询的计算列

MS SQL Server - Adding computed column with subquery

我正在尝试添加带有子查询的计算列,这将使用此查询将 Unix 时间戳转换为常规 DateTime 格式,但出现错误。 使用 Azure SQL 服务器。

ALTER TABLE dbo.FP_Contacts_CRM 
    ADD DWH_propertieslastmodifieddatevalue 
        AS (SELECT DATEADD(S, CONVERT(INT, LEFT(propertieslastmodifieddatevalue, 10)), '1970-01-01')
            FROM dbo.FP_Contacts_CRM)

我收到这个错误:

Msg 1046, Level 15, State 1, Line 12
Subqueries are not allowed in this context. Only scalar expressions are allowed

您不能对计算列使用子查询。相反,只给出公式。

alter table dbo.FP_Contacts_CRM 
add DWH_propertieslastmodifieddatevalue as 
    (
        DATEADD(S, 
                    CONVERT(int,LEFT(propertieslastmodifieddatevalue, 10))
                    , '1970-01-01')
    )

如错误所述,计算列声明不允许子查询。

但是对于原始问题,您可以使用如下所示的标量函数。

DATEADD(S, CONVERT(int,LEFT(<yourdtcolumn>, 10)), '1970-01-01')