0

How to create a computed column based on the Title nvarchar(max) column of another table?

I want to make Title in table 1 a computed column from table2 based on docId = DocId. I keep trying to add it as computed column in SSMS and it won't let me.

Table1

AssetId  Title   DocId
========================

Table2

DocId  Title      
=========================
5      Disaster       
10     Recovery        
15     Pending      
5
  • 1
    You can't create computed column using another table column. Commented Jan 28, 2013 at 15:39
  • can you explain what a computed column is? in term of values in varchar. Commented Jan 28, 2013 at 15:39
  • Why would you want that computed column to exist?. You want to not write the JOIN? Commented Jan 28, 2013 at 15:41
  • 1
    Are you trying to make a computed column based on another column in a different table? That would fall under the topic of view. Commented Jan 28, 2013 at 15:43
  • Whilst a view is preferable, I suppose you could create a function to look at the other table, then use that in the definition of the computed column. Not very efficient though! Commented Jan 28, 2013 at 15:46

2 Answers 2

2

The definition of computed columns explicitly states that the columns must be in the same table (here).

What you probably want is a view.

create view vw_table1 as
    select t.AssetId, d.Title, t.docid
    from table1 t left outer join
         table2 d
         on t.docid = d.docid
Sign up to request clarification or add additional context in comments.

Comments

1

You can't create computed column using another table column. But you can define Table 1 as AssetId, DocId and create view as you desired.

CREATE VIEW YouVIEW
AS
SELECT T1.AssetId, T1.DocId, T2.Title
FROM Table1 T1
    JOIN Table2 T2
       ON T1.DocId = T2.DocId

This is parametrized inline function

CREATE FUNCTION dbo.GetValue (@DocId INT)
RETURNS TABLE
AS
RETURN
    (SELECT T1.AssetId, T1.DocId, T2.Title 
     FROM Table1 T1 
        JOIN Table2 T2 
           ON T1.DocId = T2.DocId 
     WHERE T1.DocID = @DocId
    )
GO

3 Comments

How would the function look? The view is working, thanks for the view!
Why you want to use function. The view is most applicable for your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.