Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formula for computed column based on different table's column

Consider this table: c_const

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

and another table t_anytable

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

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) 

This produces an error:

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?

like image 906
Adnan M. TÜRKEN Avatar asked May 04 '10 21:05

Adnan M. TÜRKEN


People also ask

Can a computed column reference another table?

While you can't reference another table's column directly within your expression, you can invoke a user-defined function. And therefore, you could create a user-defined function that performs the calculation you need, then simply call that function as your computed column's expression.

How do you use a computed column in SQL How do you name the computed column?

Go to your database, right click on tables, select “New Table” option. Create all columns that you require and to mark any column as computed, select that column and go to column Properties window and write your formula for computed column.

How do I find the computed column in SQL Server?

Get a list of computed columns in a SQL Server database. We can use the system function sys. computed_columns and join it with the sys. objects to get a list of available computed columns, their data type, and the column definition (formula).

How create computed column in SQL Server explain with example?

Use SQL Server Management StudioRight-click Columns and select New Column. Enter the column name and accept the default data type (nchar(10)). The Database Engine determines the data type of the computed column by applying the rules of data type precedence to the expressions specified in the formula.


1 Answers

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) 
like image 159
marc_s Avatar answered Sep 21 '22 02:09

marc_s