在SQL Server中,计算列是根据其他列的值来动态计算生成的列。如果计算列是非确定性的,即计算列的值无法确定或不稳定,则无法持久化该列。下面是一个解决方法的代码示例:
首先,创建一个示例表格:
CREATE TABLE Customers (
CustomerID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
BirthDate DATE,
Age AS DATEDIFF(YEAR, BirthDate, GETDATE()) -- 计算列
)
如果在创建计算列时,遇到了无法持久化的错误,可以采取以下解决方法之一:
ALTER TABLE Customers ADD AgePersisted INT
-- 更新新列的值
UPDATE Customers SET AgePersisted = DATEDIFF(YEAR, BirthDate, GETDATE())
CREATE VIEW vwCustomers AS
SELECT CustomerID, FirstName, LastName, BirthDate, DATEDIFF(YEAR, BirthDate, GETDATE()) AS Age
FROM Customers
CREATE TRIGGER trg_UpdateAge
ON Customers
AFTER INSERT, UPDATE
AS
BEGIN
UPDATE Customers
SET Age = DATEDIFF(YEAR, BirthDate, GETDATE())
FROM Customers
INNER JOIN inserted ON Customers.CustomerID = inserted.CustomerID
END
需要注意的是,以上解决方法适用于无法持久化的计算列。根据具体情况选择适合的解决方法。