Data in column not changed
I have sql 2005 and when i run below query, data from RealTimeLog table transfer to History but when new data come in RealTimeLog table old data not changed by new one means OutTime data is not changed with new data from RealTimeLog.
INSERT INTO History
(UserID,
UserName,
LogDate,
[InTime],
[OutTime])
SELECT UserID,
UserName,
[LogDate],
CONVERT(NVARCHAR, MIN(CONVERT(开发者_JS百科DATETIME, [LogTime], 108)), 108),
CONVERT(NVARCHAR, MAX(CONVERT(DATETIME, [LogTime], 108)), 108)
FROM RealTimeLog
WHERE NOT EXISTS (SELECT *
FROM History H
WHERE H.UserID = RealTimeLog.UserID
AND H.UserName = RealTimeLog.UserName
AND H.LogDate = RealTimeLog.LogDate)
GROUP BY UserID,
UserName,
[LogDate]
ORDER BY UserID,
[LogDate]
for ex.
1 Shanks 02/05/2010 9:00 10:00
if new Max time generated suppose 11:00 in RealtimeLog then it is not inserted in History table and output remain same as above.
As it´s explicitly in your condition, you just insert new records when it brigs a new userid or new user name or new LogDate. In the case that you show this condition is not met.
You have to add an update clause after that for the cases where the Log already exists ... where Exists...
or inner join
as follows:
UPDATE H
SET [OutTime] = CONVERT(NVARCHAR,MAX(CONVERT(DATETIME,R.[LogTime],108)),108)
FROM History H inner join
RealTimeLog R ON H.UserID = R.UserID
AND H.UserName = R.UserName
AND H.LogDate = R.LogDate
GROUP BY H.UserID,
H.UserName,
H.LogDate
HAVING [OutTime]<>CONVERT(NVARCHAR,MAX(CONVERT(DATETIME,R.[LogTime],108)),108)
In SQL Server 2008, a nice approach is the MERGE syntax: http://technet.microsoft.com/en-us/library/bb510625.aspx
精彩评论