如果存在则将isNull替换为

时间:2018-06-21 11:04:31

标签: sql sql-server if-statement isnull

我有一个存储过程,其中它不能返回任何行,在这种情况下,我想将“ Other”作为值。 我的过程设置了列“ @col”的值,我尝试使用ISNULL,但这是错误的

update cal
set '+@col+' = isnull(p.par_name, ''Other'')
from #CALENDAR cal
inner join #WEBSITES w on w.par_id = cal.par_id and
    (
        w.bur_id = cal.bur_id
        or
        (w.date = cal.Date or (w.[date] is null and cal.Date is null))
    )
left join partner p on p.par_id = isnull(w.par_id,-1) AND tpa_id = 3 -- partner de type advertiser
where website_id ='+convert(varchar(3), @wid)

我试图像这样放置一个IF EXIST,但是没有用:

update cal
set '+@col+' = if exists (p.par_name
from #CALENDAR cal
inner join #WEBSITES w on w.par_id = cal.par_id and
    (
        w.bur_id = cal.bur_id
        or
        (w.date = cal.Date or (w.[date] is null and cal.Date is null))
    )
left join partner p on p.par_id = isnull(w.par_id,-1) AND tpa_id = 3 -- partner de type advertiser
where website_id ='+convert(varchar(3), @wid)+') else ''Other'' '

为简化查询,我要做的是(混合sql和c#):

if(w.par_id = null)
 select p.par_name from partner p where p.par_id = -1 <= will return nothing, an empty row
THEN if(p.par_name is EMPTY) THEN p.par_name='Other'

不返回任何行,在这种情况下,我想输入“其他”

3 个答案:

答案 0 :(得分:1)

您可以使用一些选项:

  1. @@ ROWCOUNT:请进行常规选择并向后检查@@ROWCOUNT的值,如果它是0,则前一条语句返回0行,因此您可以执行另外的{{ 1}}和您的硬编码值。

    SELECT
  2. 在C#代码中验证结果集。检查结果集是否有0行,然后直接在C#中生成您的值。

  3. 针对您的结果集,对生成了1行的表格进行SELECT p.par_name FROM #CALENDAR WHERE --... IF @@ROWCOUNT = 0 BEGIN SELECT 'Other' AS par_name END

    LEFT JOIN

请勿使用SELECT ISNULL(X.par_name, G.par_name) AS par_name FROM (VALUES ('Other')) AS G(par_name) LEFT JOIN ( SELECT p.par_name from #CALENDAR cal inner join #WEBSITES w on w.par_id = cal.par_id and ( w.bur_id = cal.bur_id or (w.date = cal.Date or (w.[date] is null and cal.Date is null)) ) left join partner p on p.par_id = isnull(w.par_id,-1) AND tpa_id = 3 -- partner de type advertiser where website_id = '+convert(varchar(3), @wid)' ) AS X ON G.par_name = X.par_name ,因为您将被迫重复查询,从而导致额外的维护工作。

答案 1 :(得分:1)

函数isnull(p.par_name, ''Other'')仅在选择返回1行且列par_nameNULL的情况下起作用。

要解决此问题,请在没有选择的情况下首先设置变量名称,然后再执行选择。像这样...

-- set value in case no rows are found
set @col = 'Other'

-- if a row is found and there is a null, set the value again to Other
select @col = isnull(p.par_name, 'Other')
from #CALENDAR cal
inner join #WEBSITES w on w.par_id = cal.par_id and
    (
        w.bur_id = cal.bur_id
        or
        (w.date = cal.Date or (w.[date] is null and cal.Date is null))
    )
left join partner p on p.par_id = isnull(w.par_id,-1) AND tpa_id = 3 -- partner de type advertiser
where website_id ='+convert(varchar(3), @wid)

答案 2 :(得分:0)

您可以使用COALESCE()功能。 COALESCE()函数返回列表中的第一个非空表达式。下面是语法:

COALESCE(expr1, expr2, ...., expr_n)

expr1,expr2,expr_n-要测试的表达式/列/值