Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi guys,
Can anyone please tell me that how can i execute a same query for all the tables of a database.I am already having the names of all tables retrieved by a query i.e
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'


Query for database is that it must check the condition(where day is Monday and period4 is null) for all tables.

Please help me as soon as it could be possible as it a part of my project.
Regards,
Akkywadhwa
Posted

You can use this as a starting point:

SQL
CREATE TABLE #DBTables (Name NVARCHAR(256), ID INT IDENTITY)

INSERT #DBTables
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

DECLARE @Count INT, @RC INT
SET @RC = @@ROWCOUNT
SET @Count = 1

WHILE (@Count < @RC)
BEGIN
    DECLARE @TableName NVARCHAR(256)

    SELECT @TableName = Name FROM #DBTables WHERE ID = @Count

    DECLARE @Query NVARCHAR(MAX)

    SET @Query = 'SELECT * FROM ' + @TableName + ' WHERE Day = ''Monday'' AND Period4 = NULL'

    EXEC(@Query)

    SET @Count = @Count + 1
END

DROP TABLE #DBTables
 
Share this answer
 
Comments
Mohamed Mitwalli 15-May-12 8:06am    
5+
Manas Bhardwaj 15-May-12 8:14am    
thanks!
Akkywadhwa 15-May-12 8:39am    
Thanks Manas,
But can you tell me how can i retrieve one by one table name of the multiple resultset returned by this query.
Example:
I have to retrieve the name of table shown in resultset containing more than 2 rows.
Regards,
Akkywadhwa
Hi ,
Check this
C#
using (
              SqlConnection con =
                  new SqlConnection(ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString))
       {
           using(SqlCommand cmd = new SqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'",con))
           {
               DataTable dt = new DataTable();
               SqlDataAdapter adpt = new SqlDataAdapter(cmd);
               adpt.Fill(dt);
               foreach (DataRow row in dt.Rows)
               {
                      //Here put your condtions for cmd2
                   using (SqlCommand cmd2 = new SqlCommand("select * from " + row[0], con)) ;
                   {
                       SqlDataAdapter adpt2 = new SqlDataAdapter(cmd);
                       DataTable dt2 = new DataTable();
                       adpt2.Fill(dt2);
                   }
               }
           }
       }

Best Regards
M.Mitwalli
 
Share this answer
 
Comments
Manas Bhardwaj 15-May-12 8:14am    
nice and have my 5!
Mohamed Mitwalli 15-May-12 8:24am    
thanks :)
VJ Reddy 22-May-12 23:11pm    
Good answer. 5!
Mohamed Mitwalli 23-May-12 3:26am    
Thanks VJ :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900