USE [12369]
GO/****** Object:  Trigger [dbo].[UT_Index]    Script Date: 05/16/2011 08:50:21 ******/
SET ANSI_NULLS ON
GOSET QUOTED_IDENTIFIER ON
GO--插入序号格式(年份——00000)
CREATE TRIGGER [dbo].[UT_Index] ON [dbo].[TS_Accept] 
FOR INSERT
AS
-- 插入的行数为0
if @@rowcount=0
return
-- 读取新增加的行的信息
declare @m_id int
declare @m_last_id int
declare @m_last_numbing nvarchar(50)
declare @m_complainTime datetime
declare @m_last_complainTime datetime
select @m_id=[id],@m_complainTime=complainTime from inserted
select top 1 @m_last_id=[id], @m_last_complainTime=complainTime,@m_last_numbing=numbering from TS_Accept where numbering is not null order by id desc
begin
declare @length int
declare @numFormat nvarchar(50) --格式
declare @newNumbering nvarchar(50) --序号
if(year(@m_complainTime)>cast(substring(@m_last_numbing,1,4) as int(4)))
   begin
print '新的一年编号从00001开始'
--set @length=len(@m_id)
--set @numFormat = convert(nvarchar,year(@m_complainTime))+'-'+'00000'
--set @newNumbering = substring(@numFormat,1,10-@length)+convert(nvarchar,@m_id)
set @newNumbering = convert(nvarchar,year(@m_complainTime))+'-00001'
   end
else
   begin
print '开始计算编号'
--定义差
declare @d int
set @d = @m_id-@m_last_id
--在此基础上加上差即得到编号后面的数值位(位数不确定,因此得判断)
declare @sum int
--判断编号后面的数字位数(eg:’2008-00124‘ 即取’124‘)
declare @index int
if(substring(@m_last_numbing,6,1) <> '0')
  begin
    print '5位'
    set @index = cast(substring(@m_last_numbing,6,5) as int(5))
  end
else if(substring(@m_last_numbing,7,1) <> '0')
  begin
    print '4位'
    set @index = cast(substring(@m_last_numbing,7,4) as int(5))
  end
else if(substring(@m_last_numbing,8,1) <> '0')
  begin
    print '3位'
    set @index = cast(substring(@m_last_numbing,8,3) as int(5))
  end
else if(substring(@m_last_numbing,9,1) <> '0')
  begin
    print '2位'
    set @index = cast(substring(@m_last_numbing,9,2) as int(5))
  end
else if(substring(@m_last_numbing,10,1) <> '0')
  begin
    print '1位'
    set @index = cast(substring(@m_last_numbing,10,1) as int(5))
  end
set @sum = @index + @d
declare @len int
set @len = len(@sum)
set @newNumbering = convert(nvarchar,year(getDate()))+'-'+substring('00000',1,5-@len)+cast(@sum as nvarchar(5))
   end
update TS_Accept set numbering=@newNumbering where id=@m_id
endGO让我奇怪的是执行后涉及到cast(substring(@m_last_numbing,*,*) as int(5))的地方都报错:CAST 或 CONVERT: 为类型 'int' 指定的属性无效
(@m_last_numbing,*,*)的两个*号不定的,具体是文中出现的6组数字~~