我想在sql server的情况下创建多个if else语句。 是否有可能请给我一个例子。 在c#中,您可以在案例中编写多行语句。
是否可以在SQL Server中使用C#switch case。
我想将以下代码放在case loop
中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
我需要实现@AttributeTypeId
是1然后不同的条件。来自my@AttributeId
1 to 5
答案 0 :(得分: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 =@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
答案 1 :(得分: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