我可以在计算列 select 的情况下抛出错误吗?

Can I throw an error in a computed column select case?

我的计算列中有一个 "case when",但我不知道如何抛出异常。

这是不起作用的示例代码...

CREATE TABLE OrderDetail
( OrderID INT
, ProductID INT
, Qty INT
, OrderDate DATETIME
, ShipDate DATETIME
, STATUS AS CASE
       WHEN shipdate is NULL AND orderdate < DATEADD( dd, -7, GETDATE()) THEN 3
       WHEN shipdate is NOT NULL THEN 2
       ELSE RAISERROR ('Error in shipdate',-1,-1)
   end
 )
GO

但是无效

是否可以在计算列中引发错误?

这样是不行的。 case 表达式不能用作流程控制。具体是 documented:

The CASE expression cannot be used to control the flow of execution of Transact-SQL statements, statement blocks, user-defined functions, and stored procedures.

您可以向 table 添加检查约束,但这不允许您引发自己的自定义错误:

CREATE TABLE OrderDetail
( 
      OrderID INT
    , ProductID INT
    , Qty INT
    , OrderDate DATETIME
    , ShipDate DATETIME
    , STATUS AS CASE
                    WHEN shipdate is NULL AND orderdate < DATEADD( dd, -7, GETDATE()) THEN 3
                    WHEN shipdate is NOT NULL THEN 2
                    ELSE NULL
                END
    , CONSTRAINT Chk_OrderDetails_Dates CHECK(
        shipdate IS NOT NULL 
        OR orderdate < DATEADD( dd, -7, GETDATE())
    )

)
GO

或者您可以使用触发器 - 而不是插入和更新以仅允许日期有效的行。 就个人而言,我会选择检查约束 - 它安全且更易于编写和维护。