ahmed elbarbary

ahmed elbarbary

  • NA
  • 1.6k
  • 254.9k

How to use join without using sub query on delete

Apr 13 2020 5:16 PM
I work on sql server 2012 I need use join or any way without using subquery 
to delete records 
on this query i delete from trade code that have childcodetype and childcodevalue 
without have parentcode type and parent code value
so row number 5 and 6 will be deleted  
  1. drop table #MappingCodeValue  
  2. drop table #TradeCode  
  3. create table #MappingCodeValue  
  4.  (  
  5.  id int identity (1,1),  
  6.  ParentCodeType  nvarchar(50),  
  7.  ParentCodeValue  nvarchar(50),  
  8.  ChildCodeType  nvarchar(50),  
  9.  ChildCodeValue  nvarchar(50)  
  10.  )  
  11.  INSERT INTO #MappingCodeValue  
  12.  (ParentCodeType,ParentCodeValue,ChildCodeType,ChildCodeValue)  
  13.  VALUES  
  14.  ('ECCS-US','AB123-US','ECCS-URB','AB123-URB'),  
  15.  ('ECCS-US','AB555-US','ECCS-URB','AB555-URB'),  
  16.  ('ECCS-US','AB666-US','ECCS-URB','AB666-URB'),  
  17.  ('ECCS-US','AB778-US','ECCS-URB','AB778-URB')  
  18.   
  19.   
  20.  CREATE TABLE #TradeCode  
  21.  (  
  22.  TradeCodeId int identity(1,1),  
  23.  PartId  int,  
  24.  CodeType  nvarchar(50),  
  25.  CodeValue nvarchar(50)  
  26.  )  
  27.  insert into #TradeCode(PartId,CodeType,CodeValue)VALUES  
  28.  (1222,'ECCS-US','AB123-US'),  
  29.  (1255,'ECCS-US','AB555-US'),  
  30.  (1222,'ECCS-URB','AB123-URB'),  
  31.  (1255,'ECCS-URB','AB555-URB'),  
  32.  (1444,'ECCS-URB','AB666-URB'),  
  33.  (1931,'ECCS-URB','AB778-URB')  
  34.   
  35.  delete t   
  36. from #tradecode t   
  37. where  
  38.     not exists  
  39.         (select 1 from #mappingcodevalue pn   
  40.          where  
  41.              (t.CodeValue = pn.ParentCodeValue and t.CodeType = pn.ParentCodeType) or  
  42.              ( (t.CodeValue = pn.ChildCodeValue and t.CodeType = pn.ChildCodeType) and  
  43.                (exists(select 1 from #TradeCode p  
  44.                        where p.CodeValue = pn.ParentCodeValue and p.CodeType = pn.ParentCodeType)) ))   
  1. TradeCodeId PartId  CodeType    CodeValue  
  2. 1                   1222            ECCS-US AB123-US  
  3. 2                   1255            ECCS-US AB555-US  
  4. 3                   1222            ECCS-URB    AB123-URB  
  5. 4                   1255            ECCS-URB    AB555-URB  
  6. 5                   1444            ECCS-URB    AB666-URB  
  7. 6                   1931            ECCS-URB    AB778-URB  
 

Answers (4)