关于字段计算的问题。请高手给个提示。

jxc163 2004-03-24 09:53:41
表1
类别 缩写
鼠标 MS
键盘 KB

表2
编号 类别 型号
MS001 鼠标 双飞燕3D
MS002 鼠标 罗技
KB001 键盘 太阳花
... ...
KB010 ...

这里表2中的编号要根据类别以及本类别产品的数量自动生成。
记得以前看到一个使用日期来自动生成的。现在一时找不到请各位帮个忙!
...全文
103 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
BingJingShi 2004-03-24
  • 打赏
  • 举报
回复
declare @num as int
select @num=count(*) from tab2 (如果需要,可以加条件WHERE)
则新类别的编号为: @num+1
这样,什么时候也不会错的。速度很快。

呵呵,插播一个广告: http://www.websamba.com/helloa

完全免费的欲名、主机空间, 当日开通啊……
hanfeng120 2004-03-24
  • 打赏
  • 举报
回复
up
zjcxc 2004-03-24
  • 打赏
  • 举报
回复
--测试

--表1
create table 表1(类别 varchar(10),缩写 varchar(10))
insert 表1 select '鼠标','MS'
union all select '键盘','KB'

--表2
create table 表2(编号 char(5) primary key default '',类别 varchar(10),型号 varchar(10))
go

--处理的函数
create function f_getid(@类别 varchar(10))
returns char(5)
as
begin
declare @re char(5),@id varchar(10)

select @id=缩写 from 表1 where 类别=@类别
select @re=max(编号) from 表2
where 编号 like @id+'%'
return(@id+case when @re is null then '001'
else right('000'+cast(cast(right(@re,3) as int)+1 as varchar),3) end)
end
go

--创建触发器,自动生成编号
create trigger t_insert on 表2
instead of insert
as
declare @类别 varchar(10),@缩写 varchar(10),@id int,@编号 char(5)

select * into #t from inserted order by 类别

update #t set
@编号=case 类别 when @类别 then @编号 else dbo.f_getid(类别) end
,@缩写=case 类别 when @类别 then @缩写 else left(@编号,2) end
,@id=case 类别 when @类别 then @id+1 else right(@编号,3) end
,编号=@缩写+right('000'+cast(@id as varchar),3)
,@类别=类别

insert into 表2 select * from #t
go

--插入数据到A表
insert 表2(类别,型号)
select '鼠标','双飞燕3D'
union all select '鼠标','罗技'
union all select '键盘','太阳花'
go

--显示处理结果
select * from 表2
go

--删除测试环境
drop table 表1,表2
drop function f_getid

/*--测试结果
编号 类别 型号
----- ---------- ----------
KB001 键盘 太阳花
MS001 鼠标 双飞燕3D
MS002 鼠标 罗技

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



leeboyan 2004-03-24
  • 打赏
  • 举报
回复
select a.缩写+right('00'+convert(varchar,identity(int,1,1)),3) as 编号 from table1 where table1 a,b table2 where a.类别=b.类别
leeboyan 2004-03-24
  • 打赏
  • 举报
回复
select a.缩写+right('00'convert(varchar,identity(int,1,1)),3) as 编号 from table1 where table1 a,b table2 where a.类别=b.类别

22,300

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧