所以我用Google搜索并搜索了......是否有一种简单的方法可以将SQL表的表结构与CLR数据表进行比较?
问题在于:我们有一个返回JSON的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;
}
}
我认为像这样循环可以控制序数,如果有必要的话,但正如我在其中一篇评论中提到的那样,这并非完全必要。
答案 0 :(得分:0)
所以这似乎只是简单地完成了工作:
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
可以添加到查询中,然后也可以进行检查。