Question

I have the following simple query (sql server 2012)

SELECT T.[taskId], T.[sectionId], T.[DateAdded]
FROM [TASK] AS T 
WHERE (T.[deleted] = 0)
ORDER BY T.[DateAdded]

What I would like to do is create a computed column called type, which will be 1 if SectionId is null. If not null this will contain a foreign key for a table called Organisation. Organisation has a column called type. If the type of the joined row in organisation is 6 then my computed type value should be 2, else it will be 3.

I'm guessing a CASE would be ideal for this but I', not exactly sure how to go about it.

Was it helpful?

Solution

To project a derived column, add a join to your organisation table and derive the new column based on the various values:

SELECT T.[taskId], T.[sectionId], T.[DateAdded],
   CASE 
      WHEN SectionId IS NULL THEN 1
      WHEN o.[type] = 6 THEN 2
      ELSE 3
   END AS [type]
FROM [TASK] AS T 
   -- Applicable join condition goes here ...
   LEFT OUTER JOIN Organisation o ON t.TaskID = o.TaskID
WHERE (T.[deleted] = 0)
ORDER BY T.[DateAdded]
If you **literally** want a computed column, it will look something like this: ALTER TABLE TASK ADD [Type] AS CASE WHEN SectionId IS NULL THEN 1 WHEN (SELECT [type] FROM Organisation WHERE ... JOIN KEY) = 6 THEN 2 ELSE 3 END;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top