2

I'm making a query that will delete all rows from table1 that has its column table1.id = table2.id

table1.id column is in nvarchar(max) with an xml format like this:

<customer><name>Paulo</name><gender>Male</gender><id>12345</id></customer>

EDIT: The id column is just a part of a huge XML so the ending tag may not match the starting tag.

I've tried using name.nodes but it only applies to xml columns and changing the column datatype is not a choice, So far this is the my code using PATINDEX

DELETE t1
FROM table1 t1
WHERE PATINDEX('%12345%',id) != 0

But what I need is to search for all values from table2.id which contains like this:

12345
67890
10000
20000
30000

Any approach would be nice like sp_executesql and/or while loop, or is there a better approach than using patindex? thanks!

Cyberpau
  • 125
  • 9

2 Answers2

2
;with cteBase as (
    Select *,XMLData=cast(id as xml) From Table1
)
Select *
 From cteBase
 Where XMLData.value('(customer/id)[1]','int') in (12345,67890,10000,20000,30000)

If you are satisfied with the results, change the final Select * to Delete

John Cappelletti
  • 79,615
  • 7
  • 44
  • 66
  • Thank you so much. But unfortunately my id column is not a complete XML format. It is only a part of a huge XML so it throws an error: `XML parsing: line 1, character 27, end tag does not match start tag` Is there any other way using `PATINDEX`? – Cyberpau Sep 16 '16 at 03:27
2
Select *
--Delete A
 From Table1 A
 Join Table2 B on CharIndex('id>'+SomeField+'<',ID)>0

I don't know the name of the field in Table2. I am also assuming it is a varchar. If not, cast(SomeField as varchar(25))

EDIT - This is what I tested. It should work

Declare @Table1 table (id varchar(max))
Insert Into @Table1 values
('<customer><name>Paulo</name><gender>Male</gender><id>12345</id></customer>'),
('<customer><name>Jane</name><gender>Femail</gender><id>7895</id></customer>')

Declare @Table2 table (SomeField varchar(25))
Insert into @Table2 values
('12345'),
('67890'),
('10000'),
('20000'),
('30000')


Select *
--Delete A
 From @Table1 A
 Join @Table2 B on CharIndex('id>'+SomeField+'<',ID)>0
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66