SQL Server:没有返回null的情况

时间:2016-07-04 14:14:43

标签: sql-server select

我有以下SQL Server代码:

declare @n_count_pr int, @n_count_err int, @v_out_pr varchar(100);

begin
   set @n_count_pr = (select count (*) from table_PR)
   set @n_count_err = (select count (*) from table_err)

   if (@n_count_err > 0 AND @n_count_pr > 0)  
      set @v_out_pr = 'Output 1'
   else if (@n_count_err > 0 AND @n_count_pr = 0) 
      set @v_out_pr = 'Output 2'

   print @v_out_pr
end;

它完美无缺,但我需要一个不同的结构。

我需要一个简单的选择来做同样的事情。

你能帮帮我吗?

在上面的程序中,我只有 两个输出。 如果除输出1和输出2之外还有其他输出,则应将其丢弃。

就像:

如果i = a则输出1 否则如果i = b则输出2

但我没有别的,所以其他选择i = c或i = d,我不在乎。我想放弃这些选择。

如果我确实想要其他选项,我会这样做:

   if (@n_count_err > 0 AND @n_count_pr > 0)  
      set @v_out_pr = 'Output 1'
   else if (@n_count_err > 0 AND @n_count_pr = 0) 
      set @v_out_pr = 'Output 2'
   else
      set @v_out_pr = 'any other option'

- 找到解决方案:)

select bit from 
     (SELECT CASE 
        WHEN  (SELECT COUNT (*) FROM TABLE_ERR) > 0 AND (SELECT COUNT (*) FROM TABLE_PR) > 0 THEN 'OUTPUT 1'
        WHEN  (SELECT COUNT (*) FROM TABLE_ERR) > 0 AND (SELECT COUNT (*) FROM TABLE_PR) = 0 THEN 'OUTPUT 2'
        ELSE null
        END as bit) Mytable
        where bit is not null

3 个答案:

答案 0 :(得分:2)

试试这个:

foreach(string connectionString in Servers)
{
    using (var context = new DbContext(connectionString))
    {
      //Query code
    }
}

答案 1 :(得分:1)

您可以使用以下查询:

SELECT IIF(x.cnt1 > 0 AND y.cnt2 > 0, 'Output 1', 
          IIF(x.cnt1 = 0 AND y.cnt2 > 0, 'Output 2', NULL) AS Output
FROM (SELECT COUNT(*) FROM table_PR) AS x(cnt1)
CROSS JOIN (SELECT COUNT(*) FROM table_err) AS y(cnt2)

答案 2 :(得分:1)

你也可以试试这个:

SELECT  CASE WHEN T.C1 > 0 AND T.C2 > 0 THEN 'OutPut1'
             WHEN T.C1 > 0 AND T.C2 = 0 THEN 'OutPut2'
    END AS Col
FROM    ( SELECT    T1.C1 ,
                    T2.C2
      FROM      ( SELECT    COUNT(*) AS C1
                  FROM      table_ERR
                ) AS T1
                CROSS JOIN ( SELECT COUNT(*) AS C2
                             FROM   table_PR
                           ) AS T2
    ) AS T;