2011-08-03 57 views
4

爲什麼這回空?的ExecuteScalar總是調用標量值函數時返回null

//seedDate is set to DateTime.Now; con is initialized and open. Not a problem with that 
using (SqlCommand command = new SqlCommand("fn_last_business_date", con)) 
{ 
     command.CommandType = CommandType.StoredProcedure; 
     command.Parameters.AddWithValue("@seed_date", seedDate);//@seed_date is the param name 
     object res = command.ExecuteScalar(); //res is always null 
} 

但是,當我直接在數據庫中調用這個如下:

select dbo.fn_last_business_date('8/3/2011 3:01:21 PM') 
returns '2011-08-03 15:01:21.000' 

這是結果,我希望看到,當我把它從代碼

爲什麼,爲什麼,爲什麼?

回答

7

嘗試:

using (SqlCommand command = new SqlCommand("select dbo.fn_last_business_date(@seed_date)", con)) 
{ 
     command.CommandType = CommandType.Text; 
     command.Parameters.AddWithValue("@seed_date", seedDate);//@seed_date is the param name 
     object res = command.ExecuteScalar(); //res is always null 
} 
+0

我沒有問題,返回值f rom的SQL函數。它做它應該做的。我的問題是在C#代碼。我不明白爲什麼如果我傳入一個有效的@seed_date,結果總是爲空;如果有幫助,我可以粘貼sql_function代碼。關於我的sql_function唯一特別的是它使用遞歸...可能是我的問題?那會很奇怪。 – Icarus

+0

實際上是fn_last_business_date存儲過程嗎?如果不能確保你添加的選擇,使命令類型文本(見我的編輯) –

+0

呵呵呵,我只是回答GBN,我曾想過這樣做,但我認爲這是不優雅;)我會嘗試它,如果它的作品,我會給你應有的信貸。謝謝。 – Icarus

1

你實際上得到的是不被抓的錯誤。您不會調用標量udfs,就像調用存儲過程一樣。

無論包裹UDF中存儲的過程,或改變的語法。我實際上並不知道那是什麼,因爲它是不常見的...

啊哈:看到這些問題:

+0

謝謝,你有一個關於如何調用函數的例子嗎?我想創造一個像這樣的聲明:新的SqlCommand(「選擇dbo.fn_last_business_date(」 + seedDate.ToString()+「),然後做command.CommandType = CommandType.Text但沒有看‘雅’:P – Icarus

+0

你可以創建一個存儲過程來調用你的函數... –

+0

@gbn:謝謝你的鏈接,他們都很有幫助,我不知道這是在.NET中調用sql函數的「正確」方式。 。回答以及 – Icarus

22

爲什麼每個人都堅持在select語法?..

using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("calendar.CropTime", c)) 
{ 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.DateTime).Direction = ParameterDirection.ReturnValue; 
    cmd.Parameters.AddWithValue("@d", DateTime.Now); 

    cmd.ExecuteNonQuery(); 

    textBox1.Text = cmd.Parameters["@RETURN_VALUE"].Value.ToString(); 

} 
+4

不知誰沒有發表評論的downvoter實際上證明了上述錯誤的,或者只是想嘿,這就是如何我通常做 – GSerg

+0

可能第一個,我同意不與你的答案:d,它是一個功能,它應該工作,我猜他做了downvote,因爲它與帖子,文本框和日曆無關.CropTime和日期參數xD,也許對於(+1) –

+2

就像評論,如果我記得好,只是爲了馬很明顯,當你使用函數時,如果函數需要更多的參數,返回值必須是參數集合的第一個參數。 –