且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用“或” SQL中的case语句中的子句

更新时间:2023-02-05 18:28:41

不需要 CASE 声明。请尝试这样做

选择unittypeid,typename from master_unit_type 
where(@usageunitName ='kg'AND typename ='kg')
OR(@usageunitName ='pc'AND(typename ='pc'OR typename ='kg'))


尝试:

  WHERE  @ usageunitName  = '  kg'  AND  typename =  '  kg'
OR @usageunitName = ' pc' AND (typename = ' kg' typename = ' pc'))
OR (typeName = ' 跨度>)


I have a table called master_unittype where uinttypeid and typename is there.
like

unittypeid-------------typename
1-------------------------kg
2-------------------------pc


now I have to select unittypeid,typename from this table using a condition.

some another query is returning 'kg','gm','pc' etc and I'm storing it a variable named
@usageunitName.

Now if @usageunitName='kg', i have to select unittypeid,typename from the master_unittype where typename='kg'
and
if @usageunitName='pc', i have to select unittypeid,typename from the master_unittype where typename='kg' or typename='pc'

What I have tried:

declare @usageunitName varchar(50);

select @usageunitName=typename from master_product inner join master_unit_type on master_product.productUnitTypeId=master_unit_type.unittypeid where productid=1;

 
 select unittypeid,typename from master_unit_type where ((case when @usageunitName='kg' then (typename='kg')
      when @usageunitName='pc' then (typename='kg' or typename='pc')
      else typename=''
 end));

There is no need for a CASE statement at all. Try this instead
select unittypeid,typename from master_unit_type
where (@usageunitName  ='kg' AND typename = 'kg')
   OR (@usageunitName  ='pc' AND (typename = 'pc' OR typename = 'kg'))


Try:
WHERE (@usageunitName = 'kg' AND typename = 'kg')
   OR (@usageunitName = 'pc' AND (typename = 'kg' OR typename = 'pc'))
   OR (typeName = '')