[英]Replace table names occurence in SQL
它不是第一次出現。 索引后,我需要第一次出現。 您指向的問題是沒有索引的第一次出現
我有一個SQL查詢 ,我正在嘗試使用String.Replace
進行修改,但是我的代碼正在替換它找到品牌的地方,如何避免這種情況
string tempString =
"Select t0.brandid,t0.cold,t0.colm, from brands t0 where brandid=@value";
我要替換從t0到t0之前的表名稱到tempbrands的品牌
int tempindex1 = tempString.IndexOf("FROM ");
string tempString1 = tempString.Replace("brands", "tempbrands ");
預期結果是Select t0.brandid,t0.cold,t0.colm, from tempbrands t0 where brandid=@value
使用上一個鏈接的重復項,我對其進行了修改,以指定從何處開始搜索。 我不知道這是您要找的東西嗎?
string ReplaceFirst(string text, string search, string replace, string from)
{
int posFrom= text.ToLower().IndexOf(from.ToLower());
if (posFrom < 0)
{
return text;
}
int pos = text.ToLower().IndexOf(search.ToLower(),posFrom);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
用法:
string tempString1 = ReplaceFirst(tempString, "brands", "tempbrands ", "FROM");
編輯
要在兩個字符串之間替換字符串,您可以像下面這樣修改先前的方法,但是請注意,僅使用字母作為限制是不可能的。 例如,我按注釋中的要求使用“ t”作為限制,如果表名包含“ t”,則它將行不通。 您寧願使用“ t0”:
string ReplaceFirst(string text, string search, string replace, string from, string to)
{
int posFrom = text.ToLower().IndexOf(from.ToLower());
if (posFrom < 0)
{
return text;
}
int posTo = text.ToLower().IndexOf(to.ToLower(),posFrom);
if (posTo < 0)
{
return text;
}
int pos = text.ToLower().IndexOf(search.ToLower(), posFrom);
if (pos < 0 ||pos >posTo)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
用法:
string tempString1 = ReplaceFirst(tempString, "brands", "tempbrands ", "FROM","t0");
我懷疑您只想更改第一次出現 ; 您更可能希望在SQL中重命名表 。 例如,對於( brands
=> tempbrands
brands
更改):
select b1.brandId,
b2.brandId
from brands b1, -- both tables should be changed: this
brands b2 -- ... and this
where b1.brandId > b2.brandId and
b1.colm = b2.colm
您也可以在例如select
范圍內更改表名稱
select brands.brandId -- <- all these three occurences should be changed: this,
brands.colm -- ... this
from brands -- ... and this
可以通過正則表達式來實現部分解決方案(對於任意查詢都需要SQL解析器的完整解決方案):
String tempString =
"Select t0.brandid,t0.cold,t0.colm, from brands t0 where brandid=@value";
// let's change just whole words "brands" into "tempbrands"
String sql = Regex.Replace(tempString,
@"\bbrands\b",
match => "tempbrands",
RegexOptions.IgnoreCase);
為什么解決方案只是部分解決方案? SQL是比通常預期的到達語言:
select /*this brands should be left intact*/
MyField as 'another brands should be spared',
from "this strange brands table should be skipped"
簡單地做..
string tempString =
"Select t0.brandid,t0.cold,t0.colm, from brands t0 where brandid=@value";
tempString = tempString.Replace("from brands", "tempbrands");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.