我编写了此查询,它的目的是向数据库中包含信息的客户发送电子邮件。我希望它检查返回为0的任何值,而不是在@message中发送它们。我想我将需要一个if语句,但是我一直无法弄清楚如何使其工作。任何帮助表示赞赏。
查询:
select @AssignedCount = (select COUNT(*)
FROM event
where status_name = 'ASSIGNED' AND primary_unitid = NULL
OR status_name = 'ASSIGNED' AND primary_unitid = '')
select @UnitResource = (select COUNT (*)
from unit_resources
where unit_seqnum NOT IN (select unit_seqnum from unit))
select @UnitEmployee = (select COUNT (*)
from unit_employees
where unit_seqnum NOT IN (select unit_seqnum from unit))
select @LoggedOff = (select COUNT(*)
from unit
where status_name = 'LOGGED_OFF')
select @Duplicates = (SELECT ISNULL(
(select COUNT(*)
from unit
group by unitid
having COUNT(*) > 1), 0))
select @message =
'Status Report' +
' Events in assigned status with no primary unit: '
+ REPLACE((str(@AssignedCount)),' ','') +
' Un-linked unit resource table rows: '
+ REPLACE((str(@UnitResource)),' ','') +
' Un-linked Unit resource table rows: '
+ REPLACE((str(@UnitEmployee)),' ','') +
' Units with a status of Logged Off: '
+ REPLACE((str(@LoggedOff)),' ','') +
' Duplicate Units: '
+ REPLACE((str(@Duplicates)),' ','')`
答案 0 :(得分:0)
实际上,我个人可能会而不是一堆IF
语句,而是尝试这样的事情并一次性完成:
SET @message = CONCAT('Status Report',
(SELECT CONCAT(' Events in assigned status with no primary unit: ',COUNT(*))
FROM event
WHERE status_name = 'ASSIGNED'
AND primary_unitid = NULL
OR status_name = 'ASSIGNED'
AND primary_unitid = ''
HAVING COUNT(*) > 0),
((SELECT CONCAT(' Un-linked unit resource table rows: ',COUNT (*))
FROM unit_resources ur
WHERE NOT EXISTS (SELECT 1 --I changed this from a NOT IN to an EXISTS, as NOT in have behave oddly with NULLs
FROM unit u
WHERE u.unit_seqnum = ur.seqnum)
HAVING COUNT(*) > 0))); --You get the idea now
这里我还没有做很多事情,但是HAVING COUNT(*) > 0
意味着当没有相关行时,将不返回任何行(包括0
)。这意味着信息不会与@message
的值连接。
答案 1 :(得分:0)
您将必须使用if语句来动态构建字符串:
-- setting to blank; otherwise, the string would be null
set @message = ''
-- dynamically building @message with if statements
if @AssignedCount > 0
set @message = 'Status Report' +
' Events in assigned status with no primary unit: '
+ REPLACE((str(@AssignedCount)),' ','')
if @UnitResource > 0
set @message = @message + ' Un-linked unit resource table rows: '
+ REPLACE((str(@UnitResource)),' ','')
if @UnitEmployee > 0
set @message = @message + ' Un-linked Unit resource table rows: '
+ REPLACE((str(@UnitEmployee)),' ','')
if @LoggedOff > 0
set @message = @message + ' Units with a status of Logged Off: '
+ REPLACE((str(@LoggedOff)),' ','')
if @Duplicates > 0
set @message = @message + ' Duplicate Units: '
+ REPLACE((str(@Duplicates)),' ','')
-- removing leading space from @message if AssignedCount is 0
set @message = ltrim(@message)