2012-03-31 42 views
2

我需要知道如何修改一個sql,添加到每一個select sql代碼中。 我的問題是,我需要在「FROM table」+「sql_code」之後添加此sql代碼,即使「像GROUP BY」之後有某種東西。修改NHibernate中的SQL

我知道我需要使用OnPrepareStatement,我只是不知道如何編輯SqlString來這麼做!

有一兩件事,我已經試過:

public override SqlString OnPrepareStatement(SqlString sql) 
    { 
     if (sql.Parts.Cast<string>().FirstOrDefault().Trim().ToLower() != "select") 
     { 
      return sql; 
     } 
     StringBuilder novaString = new StringBuilder(sql.ToString()); 
     String corte = sql.SubstringStartingWithLast("where").ToString(); 
     if (corte != "") 
     { 
      StringBuilder sb = new StringBuilder(corte); 
      sb.Insert(0, "with(nolock) "); 
      novaString.Replace(corte, sb.ToString()); 
     } 
     else 
     { 
      novaString.Append(" with(nolock)"); 
     } 
     return new SqlString(novaString.ToString()); 
    } 

謝謝!

+0

我不知道這意味着什麼。我會的,對不起! – Leonardo 2012-03-31 15:12:51

+0

他意味着你需要在每個你以前的問題中標記一個答案爲「接受」,即如果有答案並且他們有幫助。 – gdp 2012-03-31 17:37:40

+0

是的,我得到了那部分!你對我的問題有任何想法嗎?多謝你們 ! – Leonardo 2012-04-01 05:19:12

回答

1

我對派對有點遲到,但這裏是我如何optomize我們的一些疑問。下面的需要定的SQL語句,並附加一點點到最後:

public class OptionInterceptor: EmptyInterceptor 
{ 
    public override SqlString OnPrepareStatement(SqlString sql) 
    { 
     var parameters = sql.GetParameters(); 
     var paramCount = parameters.Count(); 

     if (paramCount > 0) 
      return sql; 

     string optionString = " OPTION (OPTIMIZE FOR ("; 

     for (var i = 0; i < paramCount; i++) 
     { 
      var comma = i > 0 ? "," : string.Empty; 
      optionString = optionString + comma + "@p" + i + " UNKNOWN"; 
     } 

     optionString = optionString + "))"; 

     var builder = new SqlStringBuilder(sql); 

     builder.Add(optionString); 

     return builder.ToSqlString(); 
    } 
} 
0

有點爲時已晚,但仍。我不得不添加一個提示到生成的sql:

private class SqlLogger : EmptyInterceptor 
{ 
    private const string Select = "SELECT"; 
    private const int SelectLen = 6; 
    private const string Hint = " /*+ dynamic_sampling(0) */"; 
    private const char Param = '?'; 

    public override SqlString OnPrepareStatement(SqlString sql) 
    { 
     var s = sql.ToString().ToUpper(); 
     var start = s.IndexOf(Select, StringComparison.Ordinal); 
     if (start != -1) 
      s = s.Insert(SelectLen, Hint); 

     var builder = new SqlStringBuilder(); 
     var parts = s.Split(Param); 
     for (var i = 0; i < parts.Length - 1; i++) 
     { 
      builder.Add(parts[i]); 
      builder.AddParameter(); 
     } 
     builder.Add(parts.Last()); 
     sql = builder.ToSqlString(); 

     return sql; 
    } 
}