How to set foreign key constraints for computed fields in sql server?

Table A has a computed field called Computed1. It is persisted and non-zero. In addition, it always evaluates an expression that is char (50). It is also unique and has a unique key limitation.

Table B has the field RefersToComputed1, which should refer to the actual value of Computed1.

Attempting to create a foreign key constraint on B RefersToComputed1 that references A 'Computed1 results in the following error:

 Error SQL01268: .Net SqlClient Data Provider: Msg 1753, Level 16, State 0, Line 1 Column 'B.RefersToComputed1' is not the same length or scale as referencing column 'A.Computed1' in foreign key 'FK_B_A'. Columns participating in a foreign key relationship must be defined with the same length and scale. 

Q: Why is this error created? Are there special measures for foreign keys for computed columns, and if so, what are they?


Summary:

  • A specific problem arises from char computed fields that are varchar. Therefore, Computed1 is varchar (50), not char (50).
  • It is best for the cast to surround the computed field expression in order to force it to be used for a particular type. Credit is sent to Cade Roux for this advice.
+7
sql-server tsql sql-server-2008 foreign-keys calculated-columns
source share
3 answers

The calculated field consists of char (M), char (N), etc., which add up to M + N + .. = 50, but the calculated field itself is varchar (50). Changing RefersToComputed1 to varchar (50) instead of char (50) solves the problem.

Foreign keys of calculated fields do not require special treatment (although saving may be required in the calculated column).

+6
source share

Is RefersToComputed1 primary key of type char(50) ?

+1
source share

Is RefersToComputed1 exactly the same data type, length and sorting exactly like Computed1 ?

Double check this ... for example, do you need the last CAST or COLLATE on Computed1 to make sure that this is what you expect? I say this because the error says that 2 columns are different

Edit: char and varchar are not identical data types, so you need CAST to change it

+1
source share

All Articles