构建检查查询

时间:2012-02-07 11:01:35

标签: sql tsql

我只想用一个选择来解决这个问题。用2可以轻松解决,但我只想要一个:

想象一下这个简单的表:

create table CheckTest(
    name varchar(50)
)

我想要一个失败的查询(它将在if语句中)如果表中没有任何行或者有一行名为='test'

所以,这些是可能的情况:

--scenario 1 - no rows: should fail
truncate table CheckTest

--scenario2 - rows with value different than "test": should succeed
insert into CheckTest values ('OK')
insert into CheckTest values ('OK')


--scenario3 - 1 row with value "test" or 1 row with value "test" among other rows with value OK

insert into CheckTest values ('test')
insert into CheckTest values ('OK')
insert into CheckTest values ('OK')

我打算像这样使用支票:

if (<check>)
    print 'fail'
else
    print 'continue'

2 个答案:

答案 0 :(得分:2)

可能是这样的:

    if (select count(c1.name) + case when count(*) = 0 then 1 else 0 end
        from #CheckTest c
        left join #CheckTest c1 on c.name = c1.name and c1.name = 'test' )  > 0
    begin
       select 'fail'
    end
    else
    begin
      select 'success'
    end

答案 1 :(得分:1)

有可能,但我不会打扰。

我能想到的所有方法将其合并为一个SELECT(例如,使用COUNTDENSE_RANK)的效率低于两个单独的查询。以下是一种方式。

IF NOT EXISTS(SELECT * 
              FROM   CheckTest 
              HAVING SUM(DISTINCT CASE 
                                    WHEN name = 'test' THEN 1 
                                    ELSE 2 
                                  END) = 2) 
  PRINT 'fail' 
ELSE 
  PRINT 'continue' 
相关问题