ahmed elbarbary

ahmed elbarbary

  • NA
  • 1.6k
  • 254.7k

how to create query based on optional field on temp table ?

Jan 22 2020 7:41 AM
problem
how to create query based on optional field on temp table ?
I work on sql server 2012
I have temp table #tempsupplier have two fields
SupplierId mandatory have value
TradeCode optinal have value may be have or may be not have value
so i need
 
  1. if(tradecode have value then execute)  
  2.   
  3. do specific select   
  4.   
  5. select p.PartID, p.PartNumber,m.SupplierId,m.TradeCode from #tempsupplier m   
  6. inner join #parts p   on p.SupplierId=m.SupplierId  
  7. where not exists ( select 1 from  #TradeCodes t where t.TradeCode=m.TradeCode)   
  8.   
  9. if (tradecode not have value meaning is null then execute depend on supplier only)  
  10.   
  11. select p.PartID, p.PartNumber,m.SupplierId,m.TradeCode from #tempsupplier m   
  12. inner join #parts p   on p.SupplierId=m.SupplierId  
  13. where not exists ( select 1 from  #TradeCodes t where t.PartID=p.PartID )  

 
  1. details data as below  
  2.   
  3. create table #tempsupplier  
  4. (  
  5. SupplierId  int,  
  6. TradeCode  int  
  7. )  
  8. insert into #tempsupplier(SupplierId,TradeCode)   
  9. values   
  10. (10,15),  
  11. (11,null)  
  12.   
  13. create table #parts  
  14. (  
  15. PartID  int,  
  16. PartNumber  nvarchar(200),  
  17. SupplierId int,  
  18. TradeCode int  
  19. )  
  20.   
  21. insert into #parts  
  22. (PartID,PartNumber,SupplierId)   
  23. values  
  24. (100,'silicon',10),  
  25. (200,'motherboard',10),  
  26. (300,'iron',10),  
  27. (400,'plastic',10),  
  28. (500,'Car',11),  
  29. (600,'Bicycle',11),  
  30. (700,'plan',11)  
  31.   
  32.   
  33. create table #TradeCodes  
  34. (  
  35. PartID int,  
  36. TradeCode int  
  37. )  
  38. insert into #TradeCodes  
  39. (PartID,TradeCode)   
  40. values  
  41. (300,10),  
  42. (400,10),  
  43. (500,20)  

Answers (1)