我有功能
CREATE FUNCTION [dbo].[fn_Get_Price_For_Circulation] (@TypeID int, @Count int, @Info xml)
RETURNS float
AS
BEGIN
declare @Result float;
if @TypeID = 9
BEGIN
if @Count = 50
set @Result = 400;
else if (@Count = 100)
set @Result = 600;
else if (@Count = 250)
set @Result = 1000;
else if (@Count = 500)
set @Result = 1700;
else if (@Count = 1000)
set @Result = 2600;
else if (@Count = 2000)
set @Result = 4000;
END
RETURN @Result;
END
我有C#代码
cn.ConnectionString = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
cn.Open();
SqlCommand myCommand = new SqlCommand("[dbo].[fn_Get_Price_For_Circulation]", cn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@TypeID", SqlDbType.Int);
myCommand.Parameters["@TypeID"].Value = typeID;
myCommand.Parameters.Add("@Count", SqlDbType.Int);
myCommand.Parameters["@Count"].Value = pCount;
myCommand.Parameters.Add("@Info", SqlDbType.Xml);
myCommand.Parameters["@Info"].Value = selxml!=null? selxml.ToString():"";
return myCommand.ExecuteScalar();
当我发送@TypeID=9
,@Count=50
,@Info=""
时,C#返回null,但是当我从SQL Server Management Studio发送相同的参数时,该函数返回400.为什么?
更新:我找到了解决方案
myCommand.Parameters.Add("@ReturnValue", SqlDbType.Float);
myCommand.Parameters["@ReturnValue"].Direction = ParameterDirection.ReturnValue;
myCommand.ExecuteNonQuery();
return myCommand.Parameters["@ReturnValue"].Value;
答案 0 :(得分:0)
我看到人们在评论中说过这个,但我会把它放在代码表格中。
您尝试将用户定义函数称为存储过程。不幸的是,这些是非常不同的东西。您正在寻找的是通过SELECT
声明来呼叫它:
using (SqlCommand myCommand = new SqlCommand("SELECT fn_Get_Price_For_Circulation(@TypeID, @Count, @Info)", cn))
{
myCommand.Parameters.AddWithValue("@TypeID", typeID);
myCommand.Parameters.AddWithValue("@Count", pCount);
if (selxml == null)
myCommand.Parameters.AddWithValue("@Info", string.Empty);
else
myCommand.Parameters.AddWithValue("@Info", selxml.ToString());
return myCommand.ExecuteScalar();
}
为了便于阅读,我还冒昧地改变你的参数以使用AddWithValue
。
至于为什么它可能会返回NULL
,这是你的函数是否写得正确的问题。现在,您检查结果是否是众多值中的一个。你确定你不是要测试它们之间是否存在吗?
if @Count < 50
set @Result = 400;
else if (@Count < 100)
set @Result = 600;
else if (@Count < 250)
set @Result = 1000;
else if (@Count < 500)
set @Result = 1700;
else if (@Count < 1000)
set @Result = 2600;
else if (@Count < 2000)
set @Result = 4000;
现在,这主要是猜测。这可能不是你想要的,但是,我说这不知道你的应用程序,它似乎更有可能是你希望完成的。