如何传递动态参数

时间:2018-04-23 12:55:20

标签: c# sql-server

我在Sql函数中有两个参数(StartDate和EndDate)。我从C#Code传递输入参数。当我传递两个参数时,查询结果正常。我的问题是,如何仅传递"结束日期"没有"开始日期" (开始日期为空),因此查询结果应该全部记录,直到" EndDate"

Sql Query:

Select * from FnEmployeeProduction(?,?)

1 个答案:

答案 0 :(得分:1)

你需要向数据库发送NULL,但由于某些原因,微软在c#中发明了@JvmStatic fun getMimeType(inUrl: String?): String { if (inUrl == null) return "" val url = inUrl.replace(" ","") var type: String? = null val extension = MimeTypeMap.getFileExtensionFromUrl(url) if (extension != null) { type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase()) } if(type ==null){ val cR = WifiTalkie.getApplicationContext().contentResolver type = cR.getType(Uri.parse(url)) } if (type == null) { type = "*/*" // fallback method_type. You might set it to */* } return type }

以下是在c#

中调用函数的示例
DBNull.Value

在你的函数中你需要处理空值

DateTime? beginDate = null;
DateTime? endDate = DateTime.now;

using (SqlCommand command = new SqlCommand("select * from FnEmployeeProduction (@begin, @end)");
{  
    command.Parameters.Add("@begin", SqlDbType.DateTime).Value = (beginDate == null) ? (object)DBNull.Value : beginDate;
    command.Parameters.Add("@end", SqlDbType.DateTime).Value = (endDate == null) ? (object)DBNull.Value : endDate;

    // now you can use this command object to send to your DB
    using (SqlConnection connection = new SqlConnection(your conn string))
    {  
       connection.Open();
       command.Connection = connection;
       using (SqlDataAdapter adapter = new SqlDataAdapter(command))
       {
           adapter.Fill(your datatable);
       }
    }
}