基于不同表的列的计算列的公式 [英] formula for computed column based on different table's column

查看:57
本文介绍了基于不同表的列的计算列的公式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此表: c_const

 code  |  nvalue
 --------------
 1     |  10000
 2     |  20000  

和另一个表 t_anytable

 rec_id |  s_id  | n_code
 ---------------------
 2      |  x     | 1

目标是使 s_id 基于此公式的计算列:

The goal is to have s_id be a computed column, based on this formula:

 rec_id*(select nvalue from c_const where code=ncode)

这会产生错误:


Subqueries are not allowed in this context. Only scalar expressions are allowed.

如何使用另一个表的列作为输入来计算此计算列的值?

How can I calculate the value for this computed column using another table's column as an input?

推荐答案

您可以为此创建用户定义的函数:

You could create a user-defined function for this:

CREATE FUNCTION dbo.GetValue(@ncode INT, @recid INT)
RETURNS INT
AS 
   SELECT @recid * nvalue 
   FROM c_const 
   WHERE code = @ncode

然后使用它来定义您的计算列:

and then use that to define your computed column:

ALTER TABLE dbo.YourTable
   ADD NewColumnName AS dbo.GetValue(ncodeValue, recIdValue)

这篇关于基于不同表的列的计算列的公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆