我正在編寫一個CLR函數來解析表列並將結果寫入另一個表。基本要求是解析Detail
列,其中包含Time
部分和ID
部分。結果將是兩個ID之間的時間差。例如:在調用SQL CLR函數時出錯
例如:Time1,Id1; Time2,Id2; Time3,Id3 ...等等 Time2-Time1是Id1花費的時間,單位爲秒。
相同的函數在正常的控制檯應用程序中工作,但是當我從SQL服務器調用它時,CLR函數拋出異常。 錯誤是用戶定義例程或聚合「功能1」的執行過程中發生
一個.NET Framework錯誤: System.Security.HostProtectionException:試圖執行由所述主機CLR禁止的操作。 受保護的資源(僅適用於完全信任)是:所有 所要求的資源是:用戶界面 System.Security.HostProtectionException: 在UserDefinedFunctions.Function1(MSISDN字符串,字符串promptdetails)
我的代碼是: SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand();
int count = 0;
string PromptPart = string.Empty;
string PrevPromptPart = string.Empty;
DateTime TimePart;
TimePart = new DateTime();
DateTime PrevTimePart;
PrevTimePart = new DateTime();
TimeSpan difference;
try
{
count++;
conn.ConnectionString = "Context Connection=true";
cmd.Connection = conn;
String[] string1 = promptdetails.Split(";".ToCharArray());
foreach (var item1 in string1)
{
count++;
String[] string2 = item1.Split(",".ToCharArray());
PromptPart = string2[1];
TimePart = DateTime.ParseExact(string2[0], "M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
if (count > 1)
{
StringBuilder sbQuery = new StringBuilder(1024);
sbQuery.Append("INSERT INTO [Shami].[DBO].[data] (MSISDN,PromptID1,PromptID2,TimeDifference) VALUES");
sbQuery.Append("('");
sbQuery.Append(msisdn);
sbQuery.Append("',");
difference = TimePart.Subtract(PrevTimePart);
sbQuery.Append("'");
sbQuery.Append(PrevPromptPart);
sbQuery.Append("','");
sbQuery.Append(PromptPart);
sbQuery.Append("',");
sbQuery.Append(difference.Seconds);
sbQuery.Append(")");
string sub = string.Empty;
sub = sbQuery.ToString();
try
{
conn.Open();
cmd = new SqlCommand(sub);
SqlContext.Pipe.ExecuteAndSend(cmd);
}
catch (Exception ie)
{
Console.WriteLine("Error..");
}
}
if (count <= 1)
{
StringBuilder sbQuery = new StringBuilder(1024);
sbQuery.Append("INSERT INTO [Shami].[DBO].[data] (MSISDN,PromptID1,PromptID2,TimeDifference) VALUES");
sbQuery.Append("('");
sbQuery.Append(msisdn);
sbQuery.Append("',");
sbQuery.Append("'_'");
sbQuery.Append(",");
sbQuery.Append(PromptPart);
sbQuery.Append(",");
sbQuery.Append("'0'");
sbQuery.Append(")");
string sub = string.Empty;
sub = sbQuery.ToString();
try
{
conn.Open();
cmd = new SqlCommand(sub);
SqlContext.Pipe.ExecuteAndSend(cmd);
}
catch (Exception ie)
{
Console.WriteLine("Error..");
}
}
PrevPromptPart = PromptPart;
PrevTimePart = TimePart;
}
}
catch (Exception)
{ ;}
finally
{
conn.Close();
conn.Dispose();
cmd.Dispose();
}
return msisdn;
請讓我知道我要去哪裏錯了。我無法在CLR中調試。
一個地方你會錯了(可能是沒有直接關係的電流誤差)正在建設使用字符串生成器查詢。你應該使用參數 –
'Console.WriteLine(「Error ..」);'很可能導致它。 SQL中沒有控制檯。 – leppie
@leppie:謝謝你,你說得對。現在沒有例外:)但無法插入表格。 –