当前位置: 代码迷 >> Sql Server >> 请问一个MSSQL触发器的有关问题
  详细解决方案

请问一个MSSQL触发器的有关问题

热度:58   发布时间:2016-04-27 13:05:37.0
请教一个MSSQL触发器的问题
我有以下TB1表,

date字段取的是系统的当前的日期,但无法精确到秒,我想通过触发器当插入或更新时TB1,把date日期精确到秒并加到checkdate字段,请教各位,谢谢!

ID date checkdate

1 2010-08-10 00:00:00.000 2010-08-10 10:10:10.200
2 2010-08-10 00:00:00.000 2010-08-10 10:10:10.200
3 2010-08-10 00:00:00.000 2010-08-10 10:10:10.200



------解决方案--------------------
字段类型改为datetime,不用触发器。
------解决方案--------------------
SQL code
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([ID] int,[date] datetime,[checkdate] datetime)insert [test]select 1,'2010-08-10 00:00:00.000',null union allselect 2,'2010-08-10 00:00:00.000',null union allselect 3,'2010-08-10 00:00:00.000',nullgoif OBJECT_ID('tri_test')is not nulldrop trigger tro_testgocreate trigger tri_test on testfor updateasupdate testset [checkdate]=getdate() from inserted a where a.id=test.id--测试update testset [date]='2012-03-21 00:00:00.000' where id=1select * from test/*ID    date    checkdate1    2012-03-21 00:00:00.000    2012-04-30 10:37:50.4202    2010-08-10 00:00:00.000    NULL3    2010-08-10 00:00:00.000    NULL*/
------解决方案--------------------
SQL code
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([ID] int,[date] date,[checkdate] datetime)insert [test]select 1,'2010-08-10',null union allselect 2,'2010-08-10',null union allselect 3,'2010-08-10',nullgoif OBJECT_ID('tri_test')is not nulldrop trigger tro_testgocreate trigger tri_test on testfor insert,updateasupdate testset [checkdate]=getdate() from inserted a where a.id=test.id--测试update testset [date]='2012-03-21 00:00:00.000' where id=1insert test select 4,getdate(),nullupdate test set [date]=getdate()select * from test/*ID    date    checkdate1    2012-04-30    2012-04-30 10:42:19.3432    2012-04-30    2012-04-30 10:42:19.3433    2012-04-30    2012-04-30 10:42:19.3434    2012-04-30    2012-04-30 10:42:19.343*/
------解决方案--------------------
1楼的方法最简单,顶一下。2、3楼也行。
  相关解决方案