根据是否存在记录条目来更新列

时间:2011-07-19 17:25:15

标签: sql sql-server tsql

我有一张表,每晚记录服务器状态信息。我使用另一个表中保存的企业中的每个服务器的列表引用该表,并且针对该表运行查询以检查在过去几个小时内该服务器名的条目是否包含在Maint表中。那部分效果很好。

Lookup table:
---------------
serverID 
serverName 
isActive

Maintenance Table:
 --------------
ServerID 
ServerName 
LastAttemptedDateTimeStamp

--This part is working fine.

以下是我想要添加的功能。我想每天更新表(覆盖所有旧信息)并为查找表中的每个条目创建一条记录。如果在过去24小时内Maint表中存在查找表中服务器的条目,则在行中放入SUCCESS位(1),更新LastAttemptedDateTime和LastSuccDateTimeUpdate。

如果该表的条目不存在,则输入FAILED位(0)并且不要更新LastSuccDateTimeUpdate

Reporting Table:
----------------
-LastAttemptedDateTime
-LastSuccDateTimeUpdate
-WasSuccessfull (bit) 0 or 1

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

这是一些使用大小写的伪代码:

Update ReportingTable R
SET Col1 = SomeValue,
    Col2 = SomeOtherValue,
    WasSuccesful = CASE
                   WHEN EXISTS (SELECT 1 FROM LookupTable WHERE ...) THEN 1
                   ELSE 0
                   END

如果你完成OP中列出的表结构,我可以更具体。我假设有一种方法可以将Reporting记录与LookupMaintenance记录相关联...