Click here to Skip to main content
15,893,190 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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));
Posted
Updated 11-Mar-16 19:13pm

If you can combine the sql that would be best. For example, wherever you are SELECT @usageunitName = ... add that sql to this sql other sql in the where clause.

If you can't you have to do a dynamic sql statement, which is not preferred.

Change your sql to be a string
SQL
DECLARE @sql NVARCHAR (MAX)
SELECT @sql = 'SELECT ... FROM ... WHERE field1 = ' + @variable

EXEC (@sql)
 
Share this answer
 
WHERE

CASE WHEN (@usageunitName IS NULL OR @usageunitName='')
THEN '1'
ELSE -- Your field Name
END = CASE WHEN (@usageunitName IS NULL OR @usageunitName='')
THEN '1'
ELSE @usageunitName
END


---- add another condition as per your requirment.


Ashish
 
Share this answer
 
Comments
souvikcode 12-Mar-16 11:03am    
@usageunitName is going fine.I didn't ask case on that. I asked to use case on the last statement.
Nigam,Ashish 15-Mar-16 8:24am    
I have given u a example you can put @usageunitName='pc' instead of '' or null and put your field in place of your field, and replace " AND " in to "OR"
souvikcode 15-Mar-16 8:29am    
CASE WHEN (@usageunitName IS NULL OR @usageunitName='')
THEN '1'
ELSE -- Your field Name

This is you have written.
Can I put (myfield='pc' or myfield='kg') in place of "-- Your field Name"
on else cluse?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900