日期:2014-05-18  浏览次数:20478 次

这个自增字段,怎么写?
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

高手帮忙,谢谢!!!




------解决方案--------------------

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)