我有一个有 2 列的表:SolarDate
,GregorianDate
我有一个在 T-SQL 中将公历日期转换为太阳日期的函数。当一行插入到这个表中时,它只会填充GregorianDate
列。
我想在插入一行时,SolarDate
也填充字段。
我需要触发吗?还是别的东西?
我该怎么做?
我有一个有 2 列的表:SolarDate
,GregorianDate
我有一个在 T-SQL 中将公历日期转换为太阳日期的函数。当一行插入到这个表中时,它只会填充GregorianDate
列。
我想在插入一行时,SolarDate
也填充字段。
我需要触发吗?还是别的东西?
我该怎么做?
You could use a trigger - or just define your SolarDate
as a computed column based on that function that you have.
In that case - you need to first remove that column SolarDate
that you already have, and then add it again as a computed column:
ALTER TABLE dbo.YourTable
ADD SolarDate AS dbo.DetermineSolarDate(GregorianDate)
This would constantly and automatically determine the SolarDate
whenever you need that value, and you don't need to have a trigger in place for this to work.
您可以在使用 UDF 的表上创建计算列。
CREATE FUNCTION ArbSQ
(
@Num1 INT
)
RETURNS INT
AS
BEGIN
RETURN POWER(@Num1, 2)
END
GO
CREATE TABLE MyTable
(
MyNum INT
,MySQ AS dbo.ArbSQ(MyNum)
)
INSERT INTO MyTable
VALUES (1), (2), (3)
SELECT *
FROM MyTable
在此示例中(不再使用标量 UDF),计算列可以是PERSISTED;
CREATE TABLE MyTable
(
MyNum INT
,MySQ AS POWER(MyNum, 2) PERSISTED
)
INSERT INTO MyTable
VALUES (1), (2), (3)
SELECT *
FROM MyTable