How to iterate through each row in sql server?

12,246

The easiest way to do this is Try this:

SELECT 'select * from ' + name 
       + ' where row_id         like ''%1-101%'' or row_id like ''%1-102%''' 
FROM   sys.tables 
WHERE  name LIKE '%JPro_VP_Service%' 

you will get all tables together with the same conditions. You could execute them together.

Share:
12,246

Related videos on Youtube

Vishwanath Dalvi
Author by

Vishwanath Dalvi

SOreadytohelp about me box is kept "", intentionally.

Updated on June 04, 2022

Comments

  • Vishwanath Dalvi
    Vishwanath Dalvi almost 2 years

    My query returns 26 table names.

    select name from sys.tables where name like '%JPro_VP_Service%'
    

    Now I'm trying to write a query to check in every table return from the above query.

    --consider this is my first table 
    select * from JPro_VP_Service 
    where row_id like '%1-101%' or row_id like '%1-102%'
    -- likewise I want to search in 26 tables return from above query    
    

    I think I need to write for or cursor to accomplish this.

    Can anyone help me how to achieve this?

    • a_horse_with_no_name
      a_horse_with_no_name over 11 years
      This sounds like your data model could use some re-design. If that is the same data in those table, it should be stored in a single table.
  • Hanfeng
    Hanfeng over 10 years
    cte can only be used in the clause SELECT * FROM @mn=Min(rn), @mx=Max(rn) FROM cte. When cte is used in the while loop, the sql server reports an error