关于查询结果的IF语句

时间:2015-01-29 19:13:15

标签: sql sql-server tsql if-statement

我将以下查询的结果通过电子邮件发送,每天90%的时间为空。我想添加一个if语句,只发送电子邮件If(结果行数> 0)

 Select Orders.TransactionNumber, Orders.RepNumber, Orders.CustomerID,
        Orders.ShipToId, orders.ItemCode, Orders.Quantity, Orders.ReceivedDate, 
        Orders.TransmitStatus from (select TransactionNumber from Orders
 group by TransactionNumber
 having count (TransactionNumber = 1) as transa

 inner join Orders on Orders.TransactionNumber = transa.TransactionNumber

 where ItemCode = 9987 and ReceivedDate > DateAdd(day, -4, GetDate())
 order by ReceivedDate

在这里添加if (counted rows>0 send the email else end)

2 个答案:

答案 0 :(得分:1)

SQLServer中的任何DML(SELECT,INSERT,UPDATE)操作都在名为@@ROWCOUNT的全局变量中捕获。在你的情况下也可以使用它。

 Select Orders.TransactionNumber, Orders.RepNumber, Orders.CustomerID,
 Orders.ShipToId, orders.ItemCode, Orders.Quantity, Orders.ReceivedDate, 
 Orders.TransmitStatus from (select TransactionNumber from Orders
 group by TransactionNumber
 having COUNT (TransactionNumber)=1) as transa

 Inner join Orders on Orders.TransactionNumber=transa.TransactionNumber

 where ItemCode=9987 and ReceivedDate > DateADD (day, -4, GetDate() )
 Order by ReceivedDate

IF @@ROWCOUNT > 0
PRINT 'send mail<your logic goes here>'

答案 1 :(得分:0)

你无法申请:

Orders.TransactionNumber != ""

到你的where语句,以获取不空的查询结果?