【问题标题】:sql server simple insert trigger issuesql server简单插入触发器问题
【发布时间】:2011-11-14 18:01:11
【问题描述】:

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

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

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

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 

【问题讨论】:

    标签: sql sql-server triggers


    【解决方案1】:

    在声明字符数据类型时,您必须指定它们的长度,否则,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 语句中插入多条记录,此触发器将失败。您应该重写它以支持多行插入。

    【讨论】:

    • 路径变量的长度应为 260 个字符。 (如果您允许带有 \\?\ 前缀的长路径形式,则更长。)请参阅msdn.microsoft.com/en-us/library/…
    • @FilipDeVos,我赞成您的评论,因为它是针对特定情况(Windows 平台、文件路径)的绝妙建议。但是,OP 没有指定路径与什么相关(类别、Windows 路径或其他)。
    • 我假设 MS Sql Server 因此是 windows。顺便说一下,类型也应该是NVARCHAR。一次被咬,两次害羞。
    猜你喜欢
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2010-09-21
    相关资源
    最近更新 更多