简体   繁体   English

如果为null,则检查表中的SQL Server表和行

[英]Check SQL Server table and rows in table, if null create

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. 我需要一种方法来检查我的数据库中是否存在来自我的C#类的表,以及该表是否需要所需的行。 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 ) 检查是否存在SQL表

I'm working with SQL Server and C# 我正在使用SQL Server和C#

I'm going to attach a script here that will dump all the objects and columns for the objects in a TempTable. 我将在这里附加一个脚本,它将转储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 我很久以前就用过Delphi应用程序来“升级”我的数据库

I run this code on the MASTER database. 我在MASTER数据库上运行此代码。

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. 然后我将数据bcp到一个平面文件当我运行升级时,我在升级DB上创建一个具有相同结构的表,并在那里bcp主数据库的数据。

Then I used this script then in my Delphi App to check what changed. 然后我在我的Delphi应用程序中使用此脚本来检查更改的内容。

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. 如果您需要有关C#部分的更多信息,我可以给您一些代码。

Here is C# code to get you going. 这是C#代码,让你去。 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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM