title: how to get all the tables from sql server database if a column name exists in the table and save the table data in a temporary table
body: <p>I am trying to write a windows service, which will send automatic emails. all the tables which  require email sending have common columns 'templateid' and 'emailstatus'. I want to iterate through all the tables and get the tables which has column name 'templateid'.
  Now that i have the list of tables with column name 'templateid' get the data from each table whose email status is 'false' and save it in a temporary table.
  if 'table1' has 4 rows of data, the temporary table should have 4 rows. after iterating through the next table the row collection should be added to the same temporary table.</p>
  
  <pre><code>IF (SELECT object_id('TempDB..#TEMPTABLE')) IS NOT NULL
  BEGIN
      DROP TABLE #TEMPTABLE
  END
  CREATE TABLE #TEMPTABLE(
  [ID] INTEGER IDENTITY(1,1) NOT NULL,
  [TABLE_NAME] VARCHAR(1000)
  )
  INSERT INTO #TEMPTABLE(TABLE_NAME)
  SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'TEMPLATEID'
  SELECT * FROM #TEMPTABLE
  DECLARE @ROWCOUNT INT
  SET @ROWCOUNT = (SELECT COUNT(ID) FROM #TEMPTABLE) 
  DECLARE @I INT
  SET @I=1
  WHILE(@I&lt;=@ROWCOUNT)
  BEGIN
      DECLARE @TABLENAME VARCHAR(500)
          SELECT @TABLENAME=TABLE_NAME FROM #TEMPTABLE WHERE ID=@I
          EXEC('SELECT * FROM '+@TABLENAME)
      SET @I=@I+1
  END
  </code></pre>
  
  <p>i found the above query which is giving me all the tables. after that i am clueless how to proceed further as i am not good with sql server.</p>