触发器 写入数据
Posted ym296900664
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了触发器 写入数据相关的知识,希望对你有一定的参考价值。
USE [punchserver]
GO
/****** Object: Trigger [dbo].[HR_PunchRecord_insert] Script Date: 08/22/2016 08:55:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--if exists (select * from sysobjects where id=object_id(N'HR_PunchRecord_insert') and objectproperty(object_id('HR_PunchRecord_insert'),N'IsTrigger')=1)
--DROP TRIGGER
ALTER Trigger [dbo].[HR_PunchRecord_insert]
On [dbo].[tbl_realtime_glog]
for insert
as
begin
declare @FRegNo varchar(50) ,@FPunchID varchar(50),@FVerifyMode varchar(50),@FDate varchar(50),@FTime varchar(50);
SELECT @FRegNo=i.[user_id]
,@FPunchID=i.[device_id]
,@FVerifyMode=i.[verify_mode]
,@FDate=CONVERT(varchar(100), i.[io_time], 23)
,@FTime=CONVERT(varchar(100), i.[io_time], 108)
FROM Inserted i
INSERT INTO HR_PunchRecord
( [FRegNo], [FPunchID], [FVerifyMode], [FDate], [FTime],[FIsNew])
values( @FRegNo ,@FPunchID ,@FVerifyMode ,@FDate ,@FTime,'1')
end
IF OBJECT_ID('tabminuteData','U') IS NOT NULL
DROP TABLE tabminuteData
GO
CREATE TABLE tabminuteData(
TT INT,
R1H INT,
StationID INT ,
ObservTime DATETIME
)
GO
-- 创建与主表结构一致的临时表
IF object_id('Tmp_tabminuteData','U') IS NOT NULL
DROP TABLE Tmp_tabminuteData
GO
CREATE TABLE Tmp_tabminuteData(
TT INT,
R1H INT,
StationID INT ,
ObservTime DATETIME
)
GO
IF object_id('tr_Tmp_tabminuteData','TR') IS NOT NULL
DROP TRIGGER tr_Tmp_tabminuteData
GO
CREATE TRIGGER tr_Tmp_tabminuteData ON Tmp_tabminuteData
AFTER INSERT
AS
BEGIN
---- 方法一:SQL2008之后版本支持
MERGE
dbo.tabminuteData AS Target1
USING
Inserted Ins ON Ins.StationID = Target1.StationID AND Ins.ObservTime = Target1.ObservTime
WHEN MATCHED THEN
UPDATE SET Target1.TT = Ins.TT,Target1.R1H = Ins.R1H
WHEN NOT MATCHED THEN
INSERT(
tt,R1H,StationID,ObservTime)
VALUES(
tt,R1H,StationID,ObservTime);
----方法二:SQL2008以前的版本用这个方法
--UPDATE
-- tabminuteData
--SET
-- TT=b.TT,R1H=b.R1H
--FROM
-- tabminuteData a JOIN inserted b
--ON a.StationID=b.StationID AND a.ObservTime=b.ObservTime
--INSERT
-- tabMinuteData
--SELECT
-- *
--FROM
-- inserted a
--WHERE NOT EXISTS(
-- SELECT
-- TOP 1 1
-- FROM
-- tabminuteData b
-- WHERE
-- a.StationID=b.StationID AND a.ObservTime=b.ObservTime
--)
-- 最后删除临时表的数据
DELETE Tmp_tabminuteData
END
GO
-- 测试
DELETE tabminuteData
GO
INSERT dbo.Tmp_tabminuteData
( TT, R1H, StationID, ObservTime )
VALUES
(1,1,1,'2015-07-30 12:07:01'),
(2,2,2,'2015-07-30 12:07:02'),
(3,3,3,'2015-07-30 12:07:03')
GO
SELECT * FROM dbo.tabminuteData
INSERT dbo.Tmp_tabminuteData
( TT, R1H, StationID, ObservTime )
VALUES
(3,3,1,'2015-07-30 12:07:01'),
(1,1,3,'2015-07-30 12:07:03'),
(4,4,4,'2015-07-30 12:07:04')
GO
SELECT * FROM dbo.tabminuteData
SELECT * FROM dbo.Tmp_tabminuteData
以上是关于触发器 写入数据的主要内容,如果未能解决你的问题,请参考以下文章