简体   繁体   English

如何从C#在SQL存储过程中传递日期值

[英]How to pass date value in sql stored procedure from c#

I need to insert purchase date in table. 我需要在表中插入购买日期。

My table 我的桌子

purchaseDate date (data type)

C# code C#代码

string purchaseDate = "";
public string _PurchaseDate
{
    get { return purchaseDate; }
    set
    {
        DateTime purchaseDateF = DateTime.Parse(value.Trim());
        purchaseDate = purchaseDateF.ToString("dd-MM-yy");
    }
}

My stored Proc 我存储的Proc

@purchasedate,

insert into tbl_name (purchaseDate) values (@purchasedate)

If I pass purchaseDate = "29-may-14" its showing error on converting nvarchar into date. 如果我通过PurchaseDate =“ 29-may-14”,则将nvarchar转换为日期时显示错误。

Where did I make an error? 我在哪里出错?

Thanks... 谢谢...

Don't pass it as a string. 不要将其作为字符串传递。 Pass it as a date/time . 将其作为日期/时间传递。 In fact, it is very unclear to me why _PurchaseDate is a string and not a DateTime in the first place. 实际上,我不清楚_PurchaseDate为什么是string而不是DateTime But however it is stored in your app: when you add it as a parameter, convert (parse) it to a DateTime first , and add the typed date. 但是,不管它是存储在您的应用程序:当您添加它作为一个参数,转换(解析)到一个DateTime 第一 ,并添加键入日期。 Not a string . 不是string

In an ideal world: 在理想的世界中:

public DateTime PurchaseDate {get;set;}
//...
cmd.Parameters.AddWithValue("purchasedate", obj.PurchaseDate);

Then nothing more is required. 然后,仅此而已。

Instead of inserting it in a certain format, insert as normal DateTime value and then when retreieving it, convert to formatted string... 而不是以某种格式插入它,而是以正常的DateTime值插入,然后在检索时将其转换为格式化的字符串...

Change your C# datatype from string to date: 将C#数据类型从字符串更改为日期:

    public DateTime _PurchaseDate{get;set;}

Do your insert with "_PurchaseDate", I am guessing you want to display it on a client app in a certain format, so then add property like this: 用“ _PurchaseDate”进行插入,我猜您想以某种格式在客户端应用程序上显示它,因此添加如下属性:

    public string _StrPurchaseDate
    {
        get
        {
            return ((DateTime)_PurchaseDate).ToString("dd-MM-yyyy");
        }
        set
        {

        }
    }

now just retrieve the date as a string, unless you really need to store it as a certain format in sql 现在只需将日期作为字符串检索,除非您真的需要将其存储为sql中的某种格式

NOTE: If your database Date column contains NULLS, it will break when retrieving values from the database so change to nullable DateTime datatype and then check for nulls when converting: 注意:如果数据库的Date列包含NULLS,则从数据库中检索值时它将中断,因此请更改为可为null的DateTime数据类型,然后在转换时检查是否为null:

    public DateTime? _PurchaseDate{get;set;}

    public string _StrPurchaseDate
    {
        get
        {
            if (_PurchaseDate != null)
            {
                return ((DateTime)_PurchaseDate).ToString("dd-MM-yyyy");
            }
            else
            {
                return "";
            }
        }
        set
        {

        }
    }

在存储过程中使用CAST或CONVERT可以将string值转换为适当的数据库类型。

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

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