帮忙改正个触发器,谢谢!
CREATE TABLE [HMNUM] (
[HMNUM] [int] NULL DEFAULT (0),
-- [HMNUMSTRING] = [HMNUM] & ".00 " eg: HMNUM = 6543, HMNUMSTRING =6543.00
[HMNUMSTRING] [nvarchar] (20) NULL ,
[ProductIDFactory] [nvarchar] (50) NULL ,
[FACTORY] [nvarchar] (50) NULL ,
[DATE] [datetime] NULL ,
CONSTRAINT [CK HMNUM ProductIDFactory] CHECK ([ProductIDFactory] <> '/ ' and
[ProductIDFactory] <> '. ')
) ON [PRIMARY]
GO
CREATE TABLE [Product] (
[ProductID] [int] NOT NULL,
[ProductIDFactory] [nvarchar] (50),
[Colour] [nvarchar] (110) ,
[PL] [float] ,
[PW] [float] ,
[PH] [float] ,
[Weight] [float]
)
GO
现在要写个触发器,当Insert [HMNUM]([ProductIDFactory],[FACTORY]) values
( 'TestProductID01 ', 'TestFactory ')时,要实现
1. [HMNUM]=max([HMNUM])+1
2. [HMNUMSTRING] = [HMNUM] & ".00 " eg: HMNUM = 6543, HMNUMSTRING =6543.00
3. [DATE]=getdate()
而且要判断[ProductIDFactory]之前不在[HMNUM]、[Product]两个表中
以下是我自己写的
好像错误很多。。。
请帮忙指正,谢谢!!!
create trigger tr_InsertHMNum
on HMNum
instead of insert
as
declare @HMNum int
declare @HMNumString nvarchar(20)
select @HMNum=max(A.[HMNUM]),@HMNumString=cast(@HMNum as nvarchar(20)) &
'.00 ',b.ProductIDFactory,b.Factory
from HMNum as A, inserted as B
where A.[ProductIDFactory]=B.[ProductIDFactory]
IF not exists (select * from HMNum a where exists(select 1 from inserted where
ProductIDFactory=a.ProductIDFactory))
and not exists(select * from Product b where exists(select 1 from inserted where
ProductIDFactory=b.ProductIDFactory))
begin
insert HMNum values(@HMNum,@HMNumString, 'ProductIDFactory ', 'Factory ',getdate())
end
go
------解决方案--------------------create trigger tr_InsertHMNum
on HMNum
instead of insert
as
declare @HMNum int
declare @HMNumString nvarchar(20)
SET XACT_ABORT ON
BEGIN TRAN
SELECT @HMNUM=max(HMNUM)+1 from (SELECT max(HMNUM) FROM HMNum UNION ALL SELECT 0)TB
SELECT @HMNumString=cast(@HMNum as nvarchar(20)) & '.00 '
IF not exists (select * from HMNum a where exists(select 1 from inserted C where C.ProductIDFactory=a.ProductIDFactory))
and not exists(select * from Product b where exists(select 1 from inserted C where C.ProductIDFactory=b.ProductIDFactory))
begin
insert HMNum SELECT @HMNum,@HMNumString,ProductIDFactory,Factory,getdate() FROM INSERTED
end
CO