期間,當我運行的網站當SQL查詢
有一個例外消息無效的轉換異常「無法投類型的對象‘System.DBNull’鍵入 ‘System.String’。」
從下面的代碼中''return (string)c.Parameters["@vat"].Value;
'的'值'部分開始改變。我檢查了存儲過程以查看它是否執行查詢,它的確並且它的輸出也是一個字符串。任何人都可以幫助.. ??
namespace CamOnlineAccess
{
public class Utilities
{
public SqlConnection GetConnection()
{
SqlConnection c = new SqlConnection();
c.ConnectionString = ConfigurationManager.ConnectionStrings["CamOnlineConnectionString"].ConnectionString;
return c;
}
public SqlCommand GetCommandSP(string SPName)
{
SqlCommand c = new SqlCommand();
c.Connection = GetConnection();
c.CommandType = CommandType.StoredProcedure;
c.CommandText = SPName;
c.CommandTimeout = 150;
return c;
}
}
}
public string ViewUserVat(string code)
{
CamOnlineAccess.Utilities u = new CamOnlineAccess.Utilities();
SqlCommand c = u.GetCommandSP("dbo.ViewUserVat");
c.Parameters.AddRange(new System.Data.SqlClient.SqlParameter[] {
new System.Data.SqlClient.SqlParameter("@code", System.Data.SqlDbType.VarChar,50),
new System.Data.SqlClient.SqlParameter("@vat",SqlDbType.VarChar, 50, System.Data.ParameterDirection.Output, false, ((byte)(0)), ((byte)(0)), "", System.Data.DataRowVersion.Current, null)});
c.Parameters["@code"].Value = code;
c.Connection.Open();
c.ExecuteScalar();//because we have output parameters
c.Connection.Close();
return (string)c.Parameters["@vat"].Value;
}
STRORED程序
ALTER PROCEDURE [dbo].[ViewUserVat]
-- Add the parameters for the stored procedure here
@code varchar,
@vat varchar(50) output
AS
SELECT top 1 @vat=vattable from dbo.portfolio
where [email protected]
null將比'string.Empty',IMO更合適。 ''「''='null' –
我認爲返回null而不是空字符串是正確的。 –
好吧,只是假設,改變了答案,以反映@MarcGravell筆記 – Steve