比较数据表和 SQL 表

所以我用谷歌搜索并搜索......是否有一种简单的方法可以将 SQL 表的表结构与 CLR 数据表进行比较?


问题是:我们有一个返回 JSON 的 API,该 API 不断发展。当返回数组包含新对象时,我们希望通知调用者有更多数据可用。


我们可以通过查询很容易地获得 SQL 模式:


select COLUMN_NAME,ORDINAL_POSITION 

from information_schema.columns 

where table_name = 'ApiWork'

但是我们如何将列/序数与保存 JSON 数组的 DataTable 进行比较?典型的返回数组如下所示:


 {"Index_0":"930477","Index_1":"test789","ArrayID":"1","Result":"OK","Order_ID":"930477","Model_Number":"FGHB2868TF","Ship_Date":"05/30/2018","Allocated":0,"Backordered":1,"Amount":0}

我们可以使用 json 反序列化器或循环构建数据表:


DataTable dt = new DataTable();

        SqlPipe pipe = SqlContext.Pipe;

        String d = "";

        String col = "";

        int l = 0;

        int l2 = 0;

        int s = 0;

        int s2 = 0;

        o = "{\"Index_0\":\"930477\",\"Index_1\":\"test789\",\"ArrayID\":\"1\",\"Result\":\"OK\",\"DMI_Order_ID\":\"930477\",\"Model_Number\":\"FGHB2868TF\",\"Ship_Date\":\"05/30/2018\",\"Allocated\":0,\"Backordered\":1,\"Amount\":0}";

        int c = o.Length;

        while (c > 0)

        {

            col = o.Substring(0, o.IndexOf(":")).Replace("\"", "").Replace("{", "").Replace("}", "").Replace("[", "").Replace("]", "");

            dt.Columns.Add(col);

            l = o.IndexOf(":");

            l = l + 1;

            s = o.Length - l;

            o = o.Substring(l,s); // here we have removed the name portion

            l2 = o.IndexOf(",");

            l2 = l2 + 1;

            s2 = o.Length - l2;

            o = o.Substring(l2, s2); // here we have removed the value of the previous name


            c = o.Length;

            if (o.IndexOf(":") == -1 && o.IndexOf(",") == -1)

            {

                c = 0;

            }

        }

我想这样循环也可以在必要时控制序数,但正如我在我的评论中提到的那样,这并不是完全必要的。


小唯快跑啊
浏览 151回答 1
1回答

拉莫斯之舞

所以这似乎很简单:  using (SqlCommand command = new SqlCommand("Select name from tempdb.sys.COLUMNS  Where object_id=OBJECT_ID('tempdb.dbo.#ApiWork')EXCEPT Select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where table_name = 'ApiWork'"))            {                command.Connection = connection;                using (SqlDataReader reader = command.ExecuteReader())                {                    if (reader.HasRows)                    {                        pipe.Send("Something is different!");                    }else{                        pipe.Send("we're all good!");                    }                }            }可以检查这两个查询以查看列是否不同。作为旁白COLUMN_ID和ORDINAL_ID可以添加到查询中,然后也可以检查。
打开App,查看更多内容
随时随地看视频慕课网APP