简体   繁体   English

如何从C#向SQL函数传递可选参数

[英]how to pass an optional parameter to sql function from C#

I have an issue. 我有一个问题。 please help to solve my problem 请帮助解决我的问题

I have a SQL function 我有一个SQL函数

function [dbo].[fnKudishikaAmt]
    (@ParishName nvarchar(100), @Hno int, @dateto datetime = Null)
Returns Decimal(15,2)

This function shows proper result by using the execute command 通过使用execute命令,此功能可显示正确的结果

Select dbo.fnKudishikaAmt('St.George Malankara Catholic Church', 29, default)

My requirement is this function should be called from C# 我的要求是应从C#调用此函数

I am getting the error 我收到错误

Conversion failed when converting datetime from character string 从字符串转换日期时间时转换失败

Code: 码:

public double kudishikatotal(string ParishName, Int32 HouseNo)
{
    String SQLText = "select ChurchDB.dbo.fnKudishikaAmt(@ParishName, @Hno, @dateto) as fnresult";

    SqlCommand cmd = new SqlCommand(SQLText);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@ParishName", ParishName);
    cmd.Parameters.AddWithValue("@Hno", HouseNo);
    cmd.Parameters.AddWithValue("@dateto", "default");

    string rval = GetSingleValue(cmd);
    double kudiamt = 0;

    if (rval != null)
    {
        kudiamt = Convert.ToDouble(rval);
    }

    return kudiamt;
}

private static string GetSingleValue(SqlCommand cmd)
{
    string ConString = connectionstring();
    string returnvalue = "";

    using (SqlConnection con = new SqlConnection(ConString))
    {
        cmd.Connection = con;
        con.Open();
        returnvalue = cmd.ExecuteScalar().ToString();
        con.Close();
    }

    return returnvalue;
}

If you've declared default value for parameter in stored procedure - then you can just not pass this parameter from c# code at all, and in this case it will have default value. 如果您在存储过程中声明了参数的默认值,则根本无法从c#代码中传递此参数,在这种情况下,它将具有默认值。

In your case exception thrown because it's impossible to convert string "default" to SqlDateTime which is your parameter type. 在您的情况下引发异常,因为无法将字符串"default"转换为参数类型的SqlDateTime。

YOu can use if condition while sending the datetime parameter. 您可以在发送datetime参数时使用if条件。

if(some condition)
{
 cmd.Parameters.AddWithValue("@dateto", dateTimeValue);
}

Here datetimeValue is the value you want to pass. 这里datetimeValue是您要传递的值。 So you will be passing dateTimeValue only if required. 因此,仅在需要时才传递dateTimeValue。 The error is due to the string "default" you passed. 该错误归因于您传递的字符串“ default”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM