2012-12-21 60 views
0

我想在sql server的情况下创建多个if语句。 有没有可能请给我举一个例子。 在c#中,您可以在案例中编写多行语句。如何在SQL Server的Case语句内执行多个If语句

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

我希望把下面的代码的情况下,环

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

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

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

我需要实现@AttributeTypeId是1个,那么不同的条件。 [email protected] from 1 to 5

+0

你想达到什么样的SQL查询在你的问题中提到/别的条件?你能否在preudo-code代码片段中提供你的问题。 –

+1

[你有什么尝试](http://whathaveyoutried.com)?你看过BEGIN/END关键字吗? – Oded

+0

我必须在sql server中实现一种开关情况类型的条件。只是简单的查询是可能的情况下,我可以执行其他条件变化。 –

回答

2

如果您正在寻找Tsql CASE以及它是如何工作的;

--(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 [email protected] and 
     SegmentId= isnull(nullif(@SegmentId,0),SegmentId) and 
     Attribute_key like 
      case when @SegmentId > 0 and @AttributeName is not null 
      then '%'[email protected]+'%' else Attribute_key end 
     --uncomment if filter needed 
     --and AttributeID <6 
1

你可以做你的,如果使用下面

select AttributeID,Attribute_key from AttributeMaster 
where AttributeTypeId [email protected] 
and (@segmentId = 0 or [email protected]) 
and (NULLIF(@AttributeName, '') IS NULL OR 
     Attribute_key like '%'[email protected]+'%') 
order by AttributeID