日期:2014-05-17  浏览次数:20574 次

SQL server触发器问题
产品编号  varchar(10)  not null primary key;
产品名称  varchar(50)  not null;
价格          int  null;
库数量      int  null;

在表中创建触发器,向表中插入新记录时,如不给出产品名称,怎样使产品名称自动显示为产品编号?

------解决方案--------------------
update tbl_name 
set 产品名称=产品编号
where 产品名称=''
------解决方案--------------------
update 表
set 产品名称=产品编号
where isnull(产品名称,'')=''

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

-- 建测试表
create table xil
(产品编号 varchar(10) not null primary key,
 产品名称 varchar(20) not null,
 价格 int null,
 库数量 int null)

-- 建触发器
create trigger tr_xil on xil
for insert
as
begin
 update a
  set a.产品名称=a.产品编号
  from xil a
  inner join inserted b on a.产品编号=b.产品编号
  where a.产品名称=''
end
go

-- 插入新记录
insert into xil
 select 'pn001','112233',10,20 union all
 select 'pn002','',11,21 union all  -- 不给出产品名称
 select 'pn003','',12,22            -- 不给出产品名称

-- 结果
select * from xil

/*
产品编号       产品名称             价格          库数量
---------- -------------------- ----------- -----------
pn001      112233               10          20
pn002      pn002                11          21
pn003      pn003                12          22

(3 row(s) affected)
*/