我想根据同一个表中的其他列确定每一行的列值。
例如我有这张表:
BbName
DBStatus (online , offline , suspect.. etc)
IsAutoClose (0 , 1)
IsAutoCreateStatistics (0 , 1)
IsAutoShrink (0 , 1)
CheckDate (datetime)
Status(0 , 1)
每月一次,我会将数据插入这些列(DbName, DBStatus, IsAutoClose, IsAutoCreateStatistics, IsAutoShrink, CheckDate
)
我想根据该行中的其他列确定每个新行的状态列值。
像这样的东西
(IF DBStatus IN (offline, suspect) OR
IF IsAutoClose = 1 OR
IF IsAutoCreateStatistics = 0) THEN
set Status = 1
ELSE
set Status = 0
最好的方法是什么?
插入触发器后?
答案 0 :(得分:1)
完成插入后,您可以运行UPDATE
语句来更新列Status
- 如下所示:
-- update all rows with Status IS NULL to 1, if one of those
-- given conditions is met
UPDATE dbo.YourTable
SET Status = 1
WHERE Status IS NULL -- update those that have no value yet
AND (DBStatus IN (offline, suspect)
OR IsAutoClose = 1
OR IsAutoCreateStatistics = 0)
-- now update all remaining rows with Status IS NULL to 0
UPDATE dbo.YourTable
SET Status = 0
WHERE Status IS NULL -- update those that have no value yet
答案 1 :(得分:1)
如果您想在一个更新查询中进行操作,请尝试以下操作:
update Yourtable
Set Status = CASE WHEN ( DBStatus IN (offline, suspect) OR
IsAutoClose = 1 OR
IsAutoCreateStatistics = 0) THEN 1
ELSE 0
END
WHERE (...Your condition for which you want data updated...)
答案 2 :(得分:0)
将状态更改为计算列
alter table temp
add status as
case when DBStatus IN ('offline', 'suspect') then 1
when IsAutoClose = 1 then 1
when IsAutoCreateStatistics = 0 then 1
ELSE 0
end;
或者在表格顶部创建一个视图,其中包含具有该公式的状态列
答案 3 :(得分:0)
只需添加一个计算列:
alter table thistable
add status as (case when DBStatus IN (offline, suspect) OR
IsAutoClose = 1 OR
IsAutoCreateStatistics = 0
then 1 else 0
end) ;
它将在运行中计算,因此它始终是最新的。