如何根据另一列定义计算约束列
How to define calculated constrained column based on another column
我想使用 Scalar-valued function
向基于另一列的列添加默认约束
这是一个例子:
CREATE TABLE [MyTable]
(
[Id] [int] NOT NULL
[ScrambledId] [int] NOT NULL
)
ALTER TABLE [MyTable] ADD DEFAULT (dbo.MakeItScrambled([Id])) FOR [ScrambledId]
CREATE function [dbo].MakeItScrambled(@Value int)
BEGIN
--Some logic
retrun @ScrambledValue
END
我需要根据列 [Id]
对列 [ScrambledId]
进行加扰
似乎不允许使用列名:
The name "Id" is not permitted in this context. Valid expressions are
constants, constant expressions, and (in some contexts) variables.
Column names are not permitted.
有什么建议吗?
您尚未添加计算列您创建了一个普通列并尝试向其添加默认值。您不能在默认约束中引用其他列。
编辑: 这将引发错误:
Computed column 'ScrambledId' cannot be persisted because the column
is non-deterministic
如果您想要计算列,则在 table 定义中使用...
[ScrambledId] AS dbo.MakeItScrambled([Id]) PERSISTED
- 我建议在你基于标量函数计算的地方使用持久化。
或者,您可以添加一个 update/insert 触发器以在插入或更新 [Id] 时设置 [ScrambledId] 的值。
我想使用 Scalar-valued function
这是一个例子:
CREATE TABLE [MyTable]
(
[Id] [int] NOT NULL
[ScrambledId] [int] NOT NULL
)
ALTER TABLE [MyTable] ADD DEFAULT (dbo.MakeItScrambled([Id])) FOR [ScrambledId]
CREATE function [dbo].MakeItScrambled(@Value int)
BEGIN
--Some logic
retrun @ScrambledValue
END
我需要根据列 [Id]
[ScrambledId]
进行加扰
似乎不允许使用列名:
The name "Id" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
有什么建议吗?
您尚未添加计算列您创建了一个普通列并尝试向其添加默认值。您不能在默认约束中引用其他列。
编辑: 这将引发错误:
Computed column 'ScrambledId' cannot be persisted because the column is non-deterministic
如果您想要计算列,则在 table 定义中使用...
[ScrambledId] AS dbo.MakeItScrambled([Id]) PERSISTED
- 我建议在你基于标量函数计算的地方使用持久化。
或者,您可以添加一个 update/insert 触发器以在插入或更新 [Id] 时设置 [ScrambledId] 的值。