| CREATE TABLE Articles |
| ( |
| |
| [ArticleID] [int] IDENTITY (1, 1) NOT NULL , |
| [ArticleParentRef] [int] NOT NULL , |
| [ArticleNodeKey] [nvarchar](100) NULL , |
| |
| [ArtTitle] [nvarchar](200) NULL , |
| [ArtShortText] [nvarchar](600) NULL , |
| [ArtText] [nvarchar](2000) NULL , |
| [ArtTextFormat] [varchar] (10) NULL , |
| |
| [ArtUserRef] [int] NULL , |
| [ArtBlogRef] [int] NULL , |
| [ArtLanguage] [varchar] (4) NULL , |
| [ArtTime] [datetime] NULL , |
| |
| CONSTRAINT [PK_Articles] PRIMARY KEY CLUSTERED |
| ( |
| [ArticleID] ASC |
| ) |
| ) |
| |
| GO |
| |
| CREATE function dbo.fnGetArticleNodeKey( @ID int ) |
| returns nvarchar(500) |
| as |
| begin |
| declare |
| @Key nvarchar(500), |
| @SubKey nvarchar(10), |
| @ParentID int |
| |
| select @Key = N'' |
| |
| while( @ID is not NULL ) |
| begin |
| select @ParentID = ArticleParentRef from Articles where ArticleID = @ID |
| |
| set @SubKey = N'/' + right( replicate( '0', 3 ) + cast( @ID as nvarchar( 6 ) ), 4 ) |
| |
| if( charindex( @SubKey + N'/', @Key ) <> 0 ) |
| return NULL |
| |
| set @Key = @SubKey + @Key |
| set @ID = @ParentID |
| end |
| |
| return @Key |
| end |
| |
| GO |
| |
| CREATE TRIGGER tg_Articles_NodeKey |
| ON dbo.Articles |
| FOR INSERT, UPDATE |
| AS BEGIN |
| if TRIGGER_NESTLEVEL( @@PROCID ) = 1 |
| begin |
| |
| if update( ArticleID ) or update( ArticleParentRef ) or update( ArticleNodeKey ) |
| begin |
| |
| update Articles set |
| ArticleNodeKey = dbo.fnGetArticleNodeKey( ArticleID ) |
| where isNull( ArticleNodeKey, '' ) <> isNull( dbo.fnGetArticleNodeKey( ArticleID ), '' ) |
| |
| if exists( select * from Articles where ArticleNodeKey is NULL ) |
| begin |
| raiserror( 'Recursion in Tasks', 16, 1 ) |
| rollback tran |
| return |
| end |
| end |
| end |
| END |