mercredi 2 décembre 2015

c# Check if two tables exist in database

so I have database pavadinimas.mdf, which contains two tables: Vehicle and Repairs. I want to check if both tables exist in database. So, far I managed to check if one table exist, but how to check if both exist, if not create them.

Here is my code:

string tblnm = "Vehicle";
            SqlConnection conn;
            using (conn = new SqlConnection(connection))
            {
                conn.Open();           
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                cmd.CommandText = @"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES 
                       WHERE TABLE_NAME='" + tblnm + "') SELECT 1 ELSE SELECT 0"; ;
                cmd.Connection = conn;
                cmd.ExecuteNonQuery();
                int x = Convert.ToInt32(cmd.ExecuteScalar());
                conn.Close();
                if (x == 2)
                {
                    MessageBox.Show("Lentelės yra");
                }
                else
                {
                    MessageBox.Show("Lenteliu nėra.Sukuriama");
                }

Aucun commentaire:

Enregistrer un commentaire