且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

回复:通过减去 SQL Server 中的其他两列来计算列

更新时间:2023-02-05 08:53:51

首先,时间没有减法运算符.所以使用

First of all there is no substract operator for time. So using

SELECT time_in_only - time_out_only
FROM trip

你会得到:

操作数数据类型时间对于减法运算符无效.

Operand data type time is invalid for subtract operator.

如果你想要计算列,你可以先DROP column并重新创建它:

If you want computed column you can first DROP column and recreate it:

ALTER TABLE Trip
DROP COLUMN time_in_flight;

ALTER TABLE Trip
ADD time_in_flight 
  AS  DATEADD(mi, DATEDIFF(mi, time_out_only,time_in_only), CAST('00:00:00' AS TIME));

LiveDemo强>

如果不想重新创建表结构,手动计算使用UPDATE:

If you don't want to recreate table structure, and calculate manually use UPDATE:

UPDATE Trip
SET time_in_flight = DATEADD(mi, 
                  DATEDIFF(mi, time_out_only,time_in_only), CAST('00:00:00' AS TIME));

LiveDemo2强>

最后一种可能的解决方案是创建视图:

Last possible solution is to create view:

CREATE VIEW vw_Trip
AS
SELECT -- cols,
   time_in_flight = DATEADD(mi,
                 DATEDIFF(mi, time_out_only,time_in_only), CAST('00:00:00' AS TIME))
FROM Trip