简体   繁体   English

如何基于另一列定义计算的约束列

[英]How to define calculated constrained column based on another column

I would like adding a default constrain to a column based on another column using Scalar-valued function 我想使用Scalar-valued function将默认约束添加到基于另一列的列

These is an example: 这些是一个示例:

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

I need the column [ScrambledId] to be Scrambled based on column [Id] 我需要根据列[Id]对列[ScrambledId]进行加密

It seems that the Column Names are not permitted: 似乎不允许使用列名:

The name "Id" is not permitted in this context. 在这种情况下,不允许使用名称“ Id”。 Valid expressions are constants, constant expressions, and (in some contexts) variables. 有效表达式是常量,常量表达式和(在某些情况下)变量。 Column names are not permitted. 不允许使用列名。

Any suggestions? 有什么建议么?

You have not added a calculated column you have created a normal column and tried to add a default to it. 您尚未添加计算列,而已创建普通列并尝试向其添加默认值。 You cannot reference another column in a default constraint. 您不能在默认约束中引用另一列。

Edit: This will raise error: 编辑:这将引发错误:

Computed column 'ScrambledId' cannot be persisted because the column is non-deterministic 计算列'ScrambledId'无法保留,因为该列是不确定的

If you want a calculated column then in the table definition use... [ScrambledId] AS dbo.MakeItScrambled([Id]) PERSISTED - I would suggest using persisted where you are calcuting based on a scalar function. 如果要计算列,则在表定义中使用... [ScrambledId] AS dbo.MakeItScrambled([Id]) PERSISTED我建议在基于标量函数进行计算的地方使用persisted。

Alternatively you could add an update/insert trigger to set the value of [ScrambledId] when you insert or update [Id]. 或者,您可以添加一个更新/插入触发器,以在插入或更新[Id]时设置[ScrambledId]的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM