SQL SERVER:检查变量是否为空,然后为Where子句分配语句



我试图在sql中的WHERE子句中实现如下所示的东西。

if (@zipCode ==null)
begin
([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)   
end
else if(@zipCode !=null)
begin
([Portal].[dbo].[Address].PostalCode=@zipCode )
end  

我试了如下:

WHERE ((@zipCode IS NOT NULL AND ([Portal].[dbo].[Address].PostalCode=@zipCode)) OR (@zipCode IS NULL AND ([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)))

是错误的。谁能帮我把这句话准确地说出来?谢谢!

is null是我在COALESCE没有帮助时使用的语法。

试题:

if (@zipCode is null)
  begin
    ([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)   
  end
else 
  begin
    ([Portal].[dbo].[Address].PostalCode=@zipCode )
  end  

Isnull()语法是为这种事情内置的。

declare @Int int = null;
declare @Values table ( id int, def varchar(8) )
insert into @Values values (8, 'I am 8');
-- fails
select *
from @Values
where id = @Int
-- works fine
select *
from @Values
where id = isnull(@Int, 8);

对于您的示例,请记住,对于复杂的布尔逻辑,您可以将作用域更改为另一个不同变量的谓词。唯一需要注意的是,如果需要检查不同的数据类型,则需要对其进行不同的强制类型转换。因此,如果我添加另一行,但希望指定int为8,也引用类似于"repeat"的文本,我可以再次引用第一个变量的"isnull"来做到这一点,但对于不同字段的不同引用返回完全不同的结果数据类型。

declare @Int int = null;
declare @Values table ( id int, def varchar(16) )
insert into @Values values (8, 'I am 8'), (8, 'I am 8 repeat');
select *
from @Values
where id = isnull(@Int, 8)
and def like isnull(cast(@Int as varchar), '%repeat%')

is null可用于检查null数据是否来自查询,示例如下:

 declare @Mem varchar(20),@flag int
select @mem=MemberClub from [dbo].[UserMaster] where UserID=@uid
if(@Mem is null)
begin
    set @flag= 0;
end
else
begin
    set @flag=1;
end
return @flag;

试试case语句

WHERE
CASE WHEN @zipCode IS NULL THEN 1
ELSE @zipCode
END

尝试如下:

if ((select VisitCount from PageImage where PID=@pid and PageNumber=5) is NULL)
begin
    update PageImage
    set VisitCount=1
    where PID=@pid and PageNumber=@pageno
end 
else
begin
    update PageImage 
    set VisitCount=VisitCount+1
    where PID=@pid and PageNumber=@pageno
end

相关内容

最新更新