0

I need a way to check if a table exist in my database from my C# class, and if that table got the rows needed. If it doesn't exist or some of the rows are missing, I need to add those.

I've used this method but don't know how to get the missing functions in there. ( Check if a SQL table exists )

I'm working with SQL Server and C#

Community
  • 1
  • 1
Michael Tot Korsgaard
  • 3,582
  • 9
  • 47
  • 84
  • 1
    Your given link's accepted answer shows how to check if it exists. If it doesn't exist create it by using [ExecuteNonQuery on a SqlCommand](http://www.java2s.com/Code/CSharp/Database-ADO.net/CreatetablethroughSqlConnection.htm). Or wrap this in a Stored-Procedure and call that by setting the [Command's Type to StoredProcedure](http://msdn.microsoft.com/en-us/library/system.data.commandtype.aspx). – Tim Schmelter Mar 16 '12 at 09:10
  • Thanks @TimSchmelter ^^, you got a way to check if a table got a specific row like "Username"? – Michael Tot Korsgaard Mar 16 '12 at 09:12
  • That's the second step. A "row" does not contain data but it's fields. So show us some sample data that you want to check for existence. – Tim Schmelter Mar 16 '12 at 09:17
  • Sorry my bad, I normally calls columns for rows. It's the column name I need to check if exist, and then create it if it doesn't – Michael Tot Korsgaard Mar 16 '12 at 09:22

1 Answers1

2

I'm going to attach a script here that will dump all the objects and columns for the objects in a TempTable. I run the same script on the DB that I'm comparing with, and check which objects doesn't exists, and which columns in which tables does not exist, and which columns have changed. I've used a Delphi app very long ago then to "upgrade" my DB's

I run this code on the MASTER database.

If Exists(Select 1 from sysobjects where name = 'CheckTables')
  Drop Table CheckTables
GO
Select o.id oid, o.name oname, c.colid cid, c.name cname, t.name ctype, c.xusertype, c.[length] tlength, c.prec cprec, c.scale cscale, isnullable 
into CheckTables
from sysobjects o 
inner join syscolumns c on c.id = o.id
inner join systypes t on t.xusertype = c.xusertype
where o.name not like '%dt_%' and o.category <> 2 and o.type = 'U'
order by o.id, c.colid 

Delete CheckTables where oname = 'CheckTables'

Then I bcp the data into a flat file When I ran my upgrade, I create a table on the Upgrade DB with the same structure, and bcp the data of the Master DB in there.

Then I used this script then in my Delphi App to check what changed.

Select oname, cname, ctype, IsNull(tlength, 0), IsNull(cprec, 0), IsNull(cscale, 0), ctype, isnullable from CheckTables hr
where cname not in (Select name from syscolumns where id = object_id(oname)
and length = hr.tlength
and xusertype = hr.xusertype
and isnullable = hr.isnullable)
order by oname

This should get you going.

If you need more information on the C# part of it, I can give you some code.

Here is C# code to get you going. There is some stuff that you will have to add yourself, but if you strugle, let me know.

    private void UpgradeDB()
    {
        SqlConnection conn = new SqlConnection("Some Connection String");
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        conn.Open();
        cmd.CommandText = "If 1 = (Select 1 from sysobjects where id = object_id('CheckTables'))\r\n" +
                          "  Drop Table CheckTables\r\n" +
                          "Create Table CheckTables\r\n" +
                          "(oid int,\r\n" +
                          "oname varchar(50),\r\n" +
                          "colid int,\r\n" +
                          "cname varchar(50),\r\n" +
                          "ctype varchar(50),\r\n" +
                          "cxtype int,\r\n" +
                          "tlength int,\r\n" +
                          "cPrec int,\r\n" +
                          "cScale int,\r\n" +
                          "isnullable int";
        cmd.ExecuteNonQuery();

        //BCP your data from MASTER TABLE into the CheckTables of the UpgradeDB

        cmd.CommandText = "Select oname, cname, ctype, IsNull(tlength, 0), IsNull(cprec, 0), IsNull(cscale, 0), isnullable from CheckTables hr\r\n" +
                          "where cname not in (Select name from syscolumns where id = object_id(oname)\r\n" +
                          "and length = hr.tlength\r\n" +
                          "and xusertype = hr.xusertype\r\n" +
                          "and isnullable = hr.isnullable)\r\n" +
                          "order by oname";
        SqlDataReader read = cmd.ExecuteReader();
        string LastTable = "";
        bool TableExists = false;
        bool ColumnExists = false;
        while(read.Read())
        {
            if(LastTable != read[0].ToString())
            {
                LastTable = read[0].ToString();
                TableExists = false;
                if (!CheckIfTableExist(LastTable))
                    TableExists = CreateTable(LastTable);
                else
                    TableExists = true;
            }
            if (TableExists)
            {
                if (!CheckIfColumnExists(read[0].ToString(), read[1].ToString()))
                {
                    CreateColumn(read[0].ToString(), read[1].ToString(), read[2].ToString(),     
                        Convert.ToInt32(read[3].ToString()), Convert.ToInt32(read[4].ToString()), 
                        Convert.ToInt32(read[5].ToString()), Convert.ToBoolean(read[6].ToString()));
                    ColumnExists = false; //You don't want to alter the column if you just created it
                }
                else
                    ColumnExists = true;

                if(ColumnExists)
                {
                    AlterColumn(read[0].ToString(), read[1].ToString(), read[2].ToString(),  
                        Convert.ToInt32(read[3].ToString()), Convert.ToInt32(read[4].ToString()), 
                        Convert.ToInt32(read[5].ToString()), Convert.ToBoolean(read[6].ToString()));
                }
            }
        }
        read.Close();
        read.Dispose();
        conn.Close();
        cmd.Dispose();
        conn.Dispose();

    }

    private bool CheckIfTableExist(string TableName)
    {
        SqlConnection conn = new SqlConnection("Connection String");
        SqlCommand cmd = new SqlCommand();
        conn.Open();
        cmd.Connection = conn;
        cmd.CommandText = "Select IsNull(object_id('" + TableName + "'), 0)";
        Int64 check = Convert.ToInt64(cmd.ExecuteScalar());
        conn.Close();
        cmd.Dispose();
        conn.Dispose();
        return check != 0;
    }

    private bool CreateTable(string TableName)
    {
        try
        {
            //Write your code here to create your table
            return true;
        }
        catch
        {
            return false;
        }
    }

    private bool CheckIfColumnExists(string TableName, string ColName)
    {
        SqlConnection conn = new SqlConnection("Connection String");
        SqlCommand cmd = new SqlCommand();
        conn.Open();
        cmd.Connection = conn;
        cmd.CommandText = "Select IsNull(id, 0) from syscolumns where id = object_id('" + TableName + "') and name = '" + ColName + "'";
        Int64 check = Convert.ToInt64(cmd.ExecuteScalar());
        conn.Close();
        cmd.Dispose();
        conn.Dispose();
        return check != 0;
    }

    private void CreateColumn(string TableName, string ColName, string ColType, int Length, int Precision, int Scale, bool Nullable)
    {
        //Write your code here to create your column

    }

    private void AlterColumn(string TableName, string ColName, string ColType, int Length, int Precision, int Scale, bool Nullable)
    {
        //Write your code here to alter your column
    }
Jaques
  • 2,175
  • 1
  • 15
  • 34