sql server简单插入触发器问题

时间:2011-11-14 09:53:21

标签: sql sql-server triggers

我是触发器的新手。我有这样的表

CREATE TABLE [dbo].[Positions](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ParentId] [int] NOT NULL,
    [Path] [varchar](100) NULL,
    [Title] [nvarchar](200) NOT NULL,
    [Description] [nvarchar](1000) NULL
)

我正在尝试编写一个触发器,当插入记录时,触发器会更新路径。

The Path = the path of parent + / + Id of new inserted record

我有一个这样的触发器,但它一直设置1列中的Path不正确。

ALTER trigger [dbo].[ti_updatepath]
on [dbo].[Positions]
after insert 
as
begin

declare @NewId int =  (select Id from Inserted)
declare @NewParentId int = (select parentId  from Inserted)

declare @ParentPath varchar ;
set @ParentPath = (select path from positions where Id = @NewParentId)

declare @Path varchar;
set @path = @ParentPath + '/'+ convert(varchar ,@NewId)
update Positions set Path = @path where Id= @NewId
end

了解更多信息,我的表填充如下:

Id          ParentId    Path
1           0           1/          
2           1           1/2         
3           2           1/2/3       
5           2           1/2/5       
6           4           1/2/6       
7           2           1/2/7       
8           2           1/2/8       
9           2           1/2/9       
10          2           12/10       
13          2           1/2/13      
14          2           1/2/14      
15          2           1/2/15      
16          2           1/2/16      
17          8           1/2/8/17    
18          8           1/2/8/18    
19          8           1/2/8/19    
20          17          1/2/8/17/20 

1 个答案:

答案 0 :(得分:3)

声明字符数据类型时必须指定它们的长度,否则,SQL Server将假定它们的长度为1,因此它将仅显示第一个字符。

您需要将@ParentPath和@Path声明为varchar(100)(将100更改为适当)并将@NewId转换为varchar时还需要将其转换为指定长度的varchar:

declare @ParentPath varchar(100);
set @ParentPath = (select path from positions where Id = @NewParentId)

declare @Path varchar**(100);
set @path = @ParentPath + '/'+ convert(varchar(100), @NewId)
update Positions set Path = @path where Id= @NewId

请注意,如果有人在单个INSERT语句中插入多个记录,则此触发器将失败。您应该重写它以支持多行插入。