在 Table 设计中执行一条 SELECT 语句来设置一个 table 列的默认值

In the Table Design execute a SELECT statement to set the default value of a table column

这里是 table:

在 RegionID 的默认 属性 中,我想执行此 SELECT 语句以在添加新行时建立单元格的值:

select regionID from tRegion where IsNone = 1

当我尝试保存 table 设计时,我得到 “验证列 'RegionID' 的默认值时出错。

这里是 tRegion table:

Computed Column 的限制之一是它无法直接访问其 table 之外的任何列。所以你也可以创建一个 User Defined Functionas:

  -- Create UDF to use in computed column
CREATE FUNCTION UDF_GetDefaultRegionId ()
RETURNS int
AS
BEGIN
  DECLARE @DefRegionId int
  SELECT @DefRegionId = regionID 
  from tRegion 
  where IsNone = 1

  RETURN @DefRegionId
END;

然后在测试中使用 table 作为:

CREATE TABLE Test
( 
  StoreId int,
  --set default value here:
  RegionId  as ([dbo].UDF_GetDefaultRegionId())
 )  

Sample code here..。希望对您有所帮助!!!