0

我想在 sql server 的情况下创建多个 if else 语句。有可能吗,请给我一个例子。在 c# 中,您可以在 case 中编写多行语句。

在 SQL Server 中是否可以像 C# switch case 一样。

我想把下面的代码放在案例循环中

IF @SegmentId > 0 and @AttributeName IS NOT NULL   
begin
  select AttributeID,Attribute_key from AttributeMaster 
  where AttributeTypeId =@AttributeType and SegmentId=@SegmentId 
  and Attribute_key   like '%'+@AttributeName+'%' order by AttributeID
end

else IF @SegmentId = 0 and NULLIF(@AttributeName, '') IS NULL   
begin
  select AttributeID,Attribute_key from AttributeMaster 
  where AttributeTypeId =@AttributeType  order by AttributeID
end

else IF @SegmentId > 0 and NULLIF(@AttributeName, '') IS NULL   
begin
  select AttributeID,Attribute_key from AttributeMaster 
  where AttributeTypeId =@AttributeType and SegmentId=@SegmentId  
  order by AttributeID
end

我需要实现@AttributeTypeIdis 1 然后不同的条件。my@AttributeId1 to 5

4

2 回答 2

2

如果您正在寻找 TsqlCASE及其工作原理;

--(1) Simple case
case X when 1 then 'X is 1' 
       when 2 then 'X is 2' ...
       else 'X is not 1 or 2' end as colName

--(2) Searched case
case when X < 1 then 'X is less than 1' 
     when X = 1 then 'X is 1' ...
     else 'X is greater than 1' end as colName

我想你的整个东西都可以放into a single query

select AttributeID, Attribute_key 
       --uncomment next line if needed   
       --,case AttributeID when 1 then 'A' when 2 then 'B' ... end 
from  AttributeMaster
where AttributeTypeId =@AttributeType and 
      SegmentId= isnull(nullif(@SegmentId,0),SegmentId) and
      Attribute_key like 
           case when  @SegmentId > 0 and @AttributeName is not null 
           then '%'+@AttributeName+'%' else Attribute_key end
      --uncomment if filter needed
      --and AttributeID <6  
于 2012-12-21T14:11:17.223 回答
1

您可以使用下面的 sql 查询来完成问题中提到的所有 if/else 条件

select AttributeID,Attribute_key from AttributeMaster 
where AttributeTypeId =@AttributeType 
and (@segmentId = 0 or SegmentId=@SegmentId)
and (NULLIF(@AttributeName, '') IS NULL OR 
         Attribute_key   like '%'+@AttributeName+'%') 
order by AttributeID
于 2012-12-21T14:21:32.873 回答