日期:2014-05-19  浏览次数:20427 次

创建时间流水帐号列的表问题
表结构t里有一列userid,它是由年份+日期+小时+分钟+ '00 '+x组成一个字符串,其中x是自增的,从0开始.例如第一条记录

最后三位为000,第十条记录最后三位为010.
并且这个userid列是表t的主键列,请问怎么创建这个表?

我写了一个函数可以用来生成这个字符串,但还是不知道怎样创建这个主键列,这个函数用在表定义中总是出错.

--函数定义
create   function   ff(@t   datetime,@id   int)   returns   char(11)
as   begin   return   convert(char(8),@t,112)+replicate( '0 ',3-len(@id))+rtrim(@id)   end

--单独调用函数,结果符合要求
select   dbo.ff(getdate(),3)  

要达到这样主键列的要求,请问这个表定义语句应该怎么写呢?



------解决方案--------------------
老大的书上有个例子

生成流水号

--创建测试表
create table test(id varchar(18), --流水号,日期(8位)+时间(4位)+流水号(4位)
name varchar(10) --其他字段
)

go
--创建生成流水号的触发器
create trigger t_insert on test
INSTEAD OF insert
as
declare @id varchar(18),@id1 int,@head varchar(12)
select * into #tb from inserted
set @head=convert(varchar,getdate(),112)+replace(convert(varchar(5),getdate(),108), ': ', ' ')
select @id=max(id) from test where id like @head+ '% '
if @id is null
set @id1=0
else
set @id1=cast(substring(@id,13,4) as int)
update #tb set @id1=@id1+1
,id=@head+right( '0000 '+cast(@id1 as varchar),4)
insert into test select * from #tb
go


--插入数据,进行测试
insert into test(name)
select 'aa '
union all select 'bb '
union all select 'cc '

--修改系统时间,再插入数据测试一次
insert into test(name)
select 'aa '
union all select 'bb '
union all select 'cc '

--显示测试结果
select * from test


--删除测试环境
drop table test

/*--测试结果
id name
------------------ ----------
2004022720430001 aa
2004022720430002 bb
2004022720430003 cc
2004022720430004 aa
2004022720430005 bb
2004022720430006 cc

(所影响的行数为 6 行)
--*/