这个自增字段,怎么写?

bj3743 2007-01-31 09:45:35
CREATE TABLE [ProductCartons] (
[ProductID] [int] NOT NULL ,
[Carton#] [int] not null,
[CLength] [float] NULL DEFAULT (0),
[CWidth] [float] NULL DEFAULT (0),
[CHeight] [float] NULL DEFAULT (0))
GO

--ID 为1的第一个Carton,[Carton#]自增为1
insert ProductCartons([ProductID],[CLength],[CWidth],[CHeight])
values(1,18,15,19)

--ID 为1的第二个Carton,[Carton#]自增为2
insert ProductCartons([ProductID],[CLength],[CWidth],[CHeight])
values(1,36,30,38)

怎么把[Carton#]设为自增字段

如果插入新的ProductID,[Carton#]为1

如果插入的ProductID已存在,[Carton#]=该ProductID的最大[Carton#]+1

高手帮忙,谢谢!!!


...全文
204 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
scroing 2007-04-09
  • 打赏
  • 举报
回复
开始学习Trigger
非常感谢marco08(天道酬勤) !!!
bj3743 2007-01-31
  • 打赏
  • 举报
回复
开始学习Trigger
非常感谢marco08(天道酬勤) !!!
marco08 2007-01-31
  • 打赏
  • 举报
回复

CREATE TABLE [ProductCartons] (
[ID] int identity(1, 1),
[ProductID] [int] NOT NULL ,
[Carton#] [int] null,
[CLength] [float] NULL DEFAULT (0),
[CWidth] [float] NULL DEFAULT (0),
[CHeight] [float] NULL DEFAULT (0))
GO

create trigger tr on ProductCartons
for insert
as
declare @Carton int
select @Carton=max(A.[Carton#] )
from ProductCartons as A, inserted as B
where A.[ProductID]=B.[ProductID]

if @Carton is null
set @Carton=1
else
set @Carton=@Carton+1

update A set A.[Carton#]=@Carton
from ProductCartons as A, inserted as B
where A.ID=B.ID
go

insert ProductCartons([ProductID],[CLength],[CWidth],[CHeight])
values(1,18,15,19)

insert ProductCartons([ProductID],[CLength],[CWidth],[CHeight])
values(1,36,30,38)

insert ProductCartons([ProductID],[CLength],[CWidth],[CHeight])
values(2,36,30,38)

select * from ProductCartons

--result
ID ProductID Carton# CLength CWidth CHeight
----------- ----------- ----------- ----------------------------------------------------- ----------------------------------------------------- -----------------------------------------------------
1 1 1 18.0 15.0 19.0
2 1 2 36.0 30.0 38.0
3 2 1 36.0 30.0 38.0

(3 row(s) affected)
bj3743 2007-01-31
  • 打赏
  • 举报
回复
表不能设唯一约束
因为一个货号可以有多个包装规格
这个表就是用来记录某个货号不同时期的包装规格的

Trigger怎么写呢
marco08 2007-01-31
  • 打赏
  • 举报
回复
表沒有主鍵或唯一約束啊
marco08 2007-01-31
  • 打赏
  • 举报
回复
用觸發器

34,870

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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