我正在修改一个C#应用程序来遍历一堆SQL文件并用相应的表名替换视图名。
例如,一个名为" Item"的视图应该用名为" Item_mst"。
的表替换我有一个应用程序查看的映射文件,以确定要替换的表,如下所示:
VIEWNAME1,TABLENAME1_MST
VIEWNAME2,TABLENAME2_MST
问题是,有很多场景需要寻找,我在下面用一个示例SQL文件对它们进行了描述。
Select
i.item <<Matches the Item table but is actually the name of the column, no replace
,dbo.item.u_m <<Matches the Item table with DBO., replace
,lot <<Matches the lot table but is actually the name of a column, no replace
,(Select top 1 cost from itemcost) as Cost <<itemcost is a table, replace
,(Select top 1 cost2 from dbo.itemcost) as Cost2 <<matches the itemcost table with dbo., replace
From
dbo.item i <<matches the item table with dbo.,replace
cross join itemlot <<matches the itemlot table, replace
正如您所看到的,有许多不同的场景,我很难编写正则表达式/查找和替换算法来可靠地捕获每个场景。
我正在匹配dbo.tablename并且很容易替换它们,这是我遇到麻烦的剩余场景。是否有任何REGEX专家有任何想法?
以下是代码段:
//Replace all matched views with table names
for (int j = 0; j < viewCount.Count(); j++)
{
//replace for "."
curFileText = curFileText.Replace(".", "XXXPERIODXXX");
curFileText = Regex.Replace(curFileText, "dboXXXPERIODXXX" + ViewTables[0, j] + "XXXPERIODXXX", "dboXXXPERIODXXX" + ViewTables[1, j] + "XXXPERIODXXX", RegexOptions.IgnoreCase);
curFileText = curFileText.Replace("XXXPERIODXXX", ".");
//replace for "newline"
curFileText = curFileText.Replace(System.Environment.NewLine, "XXXNEWLINEXXX");
curFileText = Regex.Replace(curFileText, ViewTables[0, j] + "XXXNEWLINEXXX", ViewTables[1, j] + "XXXNEWLINEXXX", RegexOptions.IgnoreCase);
curFileText = curFileText.Replace("XXXNEWLINEXXX", System.Environment.NewLine);
//Fix .column_mst spots
curFileText = curFileText.Replace("dbo.", "XXXDBODOTXXX");
curFileText = curFileText.Replace(".", "XXXDOTXXX");
curFileText = Regex.Replace(curFileText, "XXXDOTXXX" + ViewTables[1, j], "XXXDOTXXX" + ViewTables[0, j], RegexOptions.IgnoreCase);
curFileText = curFileText.Replace("XXXDOTXXX", ".");
curFileText = curFileText.Replace("XXXDBODOTXXX", "dbo.");
//replace for " "
curFileText = curFileText.Replace(" ", "XXXSPACEXXX");
curFileText = Regex.Replace(curFileText, "dbo." + ViewTables[0, j] + "XXXSPACEXXX", "dbo." + ViewTables[1, j] + "XXXSPACEXXX", RegexOptions.IgnoreCase);
curFileText = curFileText.Replace("XXXSPACEXXX", " ");
}
答案 0 :(得分:0)
为什么不向后解决问题?根据您的RDBMS,您可以使用select table_name, view_definition from information_schema.views
之类的查询来获取所有视图名称和基础SQL的列表。在某个地方,每个视图的SQL将是一个select ... from <table name>
语句,用于仅基于单个表的视图。将这些结果复制到Sublime或Notepad ++中并使用简单的正则表达式(将([\w\W]+)(\s+from\s+)(\S+)([\w\W]+)
替换为$3
)来导出与其基础表关联的视图名称列表,如下所示:
vSomeView SomeTable
vOtherView OtherTable
完成后,再次使用正则表达式生成.Replace
链,将^([^ ])( )(\w\W)$
替换为.Replace("$1", "$3")
。将.Replace
链复制/粘贴到您用于执行此迁移的C#代码中。