2011-05-15 73 views
2

我有兩個表。事件之一和文章之一。
每個事件都有鏈接的文章,但文章可以不存在相應的事件。
我想要做的是獲得所有文章的列表,並有一個bool僞列,指示文章是否有鏈接事件。
即If在[Events]中存在行,其中ArticleID =當前ArticleID則爲true,如果不是false。sql server 2008 r2 - 條件僞列

+0

視圖你可以在這個答案。 http://stackoverflow.com/questions/5992673/get-current-record-for-a-subquery-in-t-sql/5992772#5992772 – 2011-05-15 11:05:18

+0

@Mikael Eriksson - 感謝您的評論。這也是一個很好的解決方案,但是BobTodd的一個更好,因爲它是持久的(如果我能最終得到它) – 2011-05-15 11:22:48

回答

3

使用持久化計算列

首先創建一個函數返回true或false

-- This function will provide the computed column definition 
CREATE FUNCTION udf_article_has_events (@id int) 
RETURNS bit 
WITH SCHEMABINDING 
AS 

BEGIN 

DECLARE @retval bit 

set @retval = 0 
if exists(select * from [Events] where ArticleId = @id) 
    set @retval = 1 


RETURN @retval 

END 

然後添加計算列這樣

Alter TABLE [dbo.Article] Add HasEvents As dbo.udf_events_exist(id) 
+0

@BobTodd - 只有一個問題 - 我得到以下錯誤:「計算列'HasEvents'表'cmsArticle '不能持久,因爲列是非確定性的「 – 2011-05-15 11:19:12

+0

ive添加了schemabinding屬性 – 2011-05-15 11:26:31

+0

@Elad - 我敢肯定,你將無法堅持這一點。如果從'Events'表中刪除一行,函數的值將會改變。 – 2011-05-15 11:26:32

1

如果該值一定要堅持,你在Event表上需要一個after插入和刪除觸發器來更新Article.HasEvents列

持久化的列
CREATE TRIGGER SetHAsEvents 
ON dbo.[Events] 
FOR INSERT 
AS 
    Update Article Set HasEvents = dbo.udf_article_has_events(inserted.ArticleId) 
    Where Id = inserted.ArticleId 
GO 

好處是,它可以被索引

1

製作此

SELECT *, CASE 
      WHEN E.ArticleID IS NULL THEN false 
      ELSE true 
      END as EventExist 
FROM Article A 
LEFT JOIN Events E ON A.ArticleID = E.ArticleID