我有一个商店程序,我开始难以维护。目的是使用按日,月和年存储的值更新Stats
表中的值。
这意味着我基本上编写了相同的WHERE
子句3次,只有日期比较部分和相应的DateType不同。每当我需要更改where子句时,我必须在3个位置进行相同的更改。我有很多不同的统计数据,客户要求我们经常更改它们。这是我今天/月/年创建的男性联系人的统计数据。
E.g:
UPDATE Stats
SET Content = (SELECT COUNT(*) FROM Contacts
WHERE Gender=1 AND DATEDIFF(DAY, GetDate(), Created) = 0)
WHERE DateType = 1 AND StatType = 1
UPDATE Stats
SET Content = (SELECT COUNT(*) FROM Contacts
WHERE DATEDIFF(MONTH, GetDate(), Created) = 0)
WHERE DateType = 2 AND StatType = 1
UPDATE Stats
SET Content = (SELECT COUNT(*) FROM Contacts
WHERE DATEDIFF(YEAR, GetDate(), Created) = 0)
WHERE DateType = 3 AND StatType = 1
我想要什么(但不知道怎么写)是某种商店程序,我只能通过我的条款,即exec sp_updateStatsDayMonthYear 'SELECT COUNT(*) FROM Contacts WHERE Gender=1'
。
答案 0 :(得分:0)
尝试使用案例陈述:
UPDATE Stats
SET Content = case
when
DateType=1 AND StatType=1
then (select count(*) from contacts where DATEDIFF(DAY,GetDate(),Created)=0))
when
DateType=2 AND StatType=1
then (select count(*) from contacts where DATEDIFF(DAY,GetDate(),Created)=0))
when
DateType=3 AND StatType=1
then (select count(*) from contacts where DATEDIFF(DAY,GetDate(),Created)=0))
end