if-else条件使用SQL查询不执行?

时间:2014-05-16 06:37:30

标签: sql

我想在SQL查询中使用if - else条件。下面我列出了我的查询。我收到的错误如下:

  

当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。

如何执行此查询?

if (select * from tblOfferDownloads where OfferId ='162')>0
Begin
select * from tblOfferDownloads
End
else
Begin
Select * from tbloffer
End

2 个答案:

答案 0 :(得分:3)

尝试使用EXISTS或COUNT。您收到错误,因为此SQL SELECT返回多行,并且您尝试将行集与0进行比较。

if EXISTS(select COUNT(*) from tblOfferDownloads where OfferId ='162')

if (select COUNT(*) from tblOfferDownloads where OfferId ='162')>0

答案 1 :(得分:0)

if语句应该是这样的:

if EXISTS(select NULL from tblOfferDownloads where OfferId ='162')
BEGIN
....

或计数:

if (select COUNT(*) from tblOfferDownloads where OfferId ='162')>0
BEGIN
....