Search code examples
sql-serverpatindex

PATINDEX all values of a column


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!


Solution

  • 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