Click here to Skip to main content
15,919,434 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to search if I have a Person database in my database. How can I do this?
I would like to add person to the personinformation table in the person database, if any.

What I have tried:

Database Name:Person
Database Table:PersonInformation


//I WANT TO SEARCH DBNAME CODE İN C#.How to write this search dbname code.

if( dbname !=null)
{
  dbname.Add();
}

else
{
MessageBox.Show("Db not found");
}
Posted
Updated 5-Sep-19 22:01pm
v3

The easiest query for you to run for checking a SQL Server for a particular database is to query the MasterDB for a count of databases matching that name
SQL
SELECT Count(*) FROM [Master].Sys.Databases WHERE [Name] = 'Person'
If this returns a value of 1, you can then query that PersonDB for tables matching the one that you want
SQL
SELECT Count(*) FROM Person.Information_Schema.Tables WHERE [Table_Name] = 'PersonInformation'
 
Share this answer
 
v2
Comments
Maciej Los 6-Sep-19 3:39am    
5ed!
For EF, check this:
C#
public static class DbContextExtensions
    {
        public static IEnumerable<string> GetTableNames(this DbContext @this)
        {
            var tableNames = new List<string>();

            using (var connection = @this.Database.GetDbConnection())
            {
                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT Distinct TABLE_NAME FROM information_schema.TABLES";
                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                tableNames.Add(reader.GetString(0));
                            }
                        }
                        reader.Close();
                    }
                }
                connection.Close();
            }
            return tableNames;
        }
    }

Source: How to get all table names of db using EF[^]
 
Share this answer
 

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