sql server 2008 r2 - 条件伪列

发布于 2024-11-07 15:47:37 字数 175 浏览 0 评论 0原文

我有两张桌子。一件事件和一篇文章。
每个事件都有一个链接的文章,但文章可以在没有相应事件的情况下存在。
我想要做的是获取所有文章的列表,并有一个布尔伪列来指示文章是否有链接事件。
即,如果 [Events] 中存在一行,其中 ArticleID = 当前 ArticleID,则为 true,否则为 false。

I have two tables. One of events and one of articles.
Each event has a linked article, but articles can exist without corresponding events.
What I want to do is get a list of all articles and have a bool pseudo-column that indicates if the article has a linked event or not.
i.e. If exists a row in [Events] where ArticleID = the current ArticleID then true, if not than false.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏见 2024-11-14 15:47:37

使用持久计算列

首先创建一个返回 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) 

Use a persisted computed column

First create a function to return true or 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

Then add computed column like this

Alter TABLE [dbo.Article] Add HasEvents As dbo.udf_events_exist(id) 
云胡 2024-11-14 15:47:37

从此创建一个视图

 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

Create a view from this

 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
拥醉 2024-11-14 15:47:37

如果必须保留该值,则需要在事件表上使用插入和删除后触发器来更新 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

保留列的另一个优点是它可以建立索引

If the value must be persisted, you need an after insert and delete trigger on the Event table to update the Article.HasEvents column

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

Added advantage of a persisted column is that it can be indexed

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文