--建表 CREATE TABLE [dbo].[test_table] ( [ID] [int] IDENTITY (1, 1) NOT NULL , [NAME] [varchar] (80) ) ON [PRIMARY] GO
--建立触发器 CREATE trigger test_trigger on test_table for insert as update test_table set name =substring(''''FM''''+stuff(''''00000'''',5-len(i.id)+1,len(i.id),CAST(i.id AS char(5))),1,7) from inserted i where i.id=test_table.id GO
--测试插入语句 insert into test_table select 1 union select 2 union select 3 union select 4 union select 5
如不使用identity的字段上面的触发器也可以做修改,如下:
alter trigger test_trigger on test_table for insert as declare @next_seq int select @next_seq=(select cast ((select substring(max(name),3,5) from test_table) as int)+1) update test_table set name =substring(stuff(''''FM00000'''',7-len(@next_seq)+1,len(@next_seq),cast(@next_seq as char(5))),1,7) --或者如此,这样更简单: -- set name =''''FM''''+right(''''00000''''+cast(@next_seq as varchar),5) from inserted i where i.id=test_table.id GO
问题二: 查询中实现对价格等货币值格式化为$0,000.00样式的问题,实现如下: 货币转换: select ''''$''''+convert(varchar,cast(tb字段 as money),1)
示例: select ''''$''''+convert(varchar,cast(111111.5 as money),1)
问题三: 编写触发器,对一表中插入的日期数据修改为该日期所处月份的最后一天 脚本如下: --建测试表 create table test_table ( id int IDENTITY(1,1) primary key, mytime datetime NOT NULL) GO
--建触发器 create trigger date_change_trigger on test_table for insert as update test_table set mytime = (select dateadd(ms,-3,dateadd(m,datediff(m,0,(select mytime from inserted))+1,0))) from inserted i where test_table.id=i.id GO