简体   繁体   中英

Problem: Conversion failed when converting date and/or time from character string

I'd like to get the total amount of purchases according to the current month, but in my SQL Server database I set the date field to write nvarchar(50). When the code is executed, I get an error:

Conversion failed when converting date and/or time from character string.

Is there a way to change the code to make it accept nvarchar(50) field type but I don't want to change it from database to date type I want it to work on nvarchar(50) type.

Code:

int month = Convert.ToInt32(DateTime.Now.Month.ToString());
DataTable tblItems_40 = new DataTable();
tblItems_40 = db8.readData("SELECT  SUM(Total) FROM Buy_Detalis WHERE MONTH(Date) 
         ='" + month + "' ", "");
tblItems8 = db8.readData("SELECT * From Buy_Detalis WHERE Date ='" + 
         month.ToString() + "'", "");
if (tblItems8.Rows.Count <= 0)
{
    labelControl6.Text = "0.ج.م";
}
else if (tblItems8.Rows.Count >= 1)
{
    labelControl6.Text = (tblItems_40.Rows[0][0].ToString)();
    labelControl6.Text = Decimal.Parse(labelControl6.Text).ToString("C");
}

I came up with this solution and wanted to share it with yous and it worked great for me

DataTable tblItems_40 = new DataTable();
        string d5 = DateTime.Now.Month.ToString();
        string d6 = DateTime.Now.Year.ToString();
        tblItems_40 = db4.readData("SELECT YEAR(CONVERT(date,[Buy_Detalis].[Date], 103)) as SalesYear,MONTH(CONVERT(date,[Buy_Detalis].[Date], 103)) as SalesMonth,sum(Buy_Detalis.Total) AS TotalSales FROM Buy_Detalis where YEAR(CONVERT(date,[Buy_Detalis].[Date], 103)) ='" + d6 + "' AND MONTH(CONVERT(date,[Buy_Detalis].[Date], 103)) ='" + d5+ "'  GROUP BY YEAR(CONVERT(date,[Buy_Detalis].[Date], 103)), MONTH(CONVERT(date,[Buy_Detalis].[Date], 103))  ", "");
        tblItems8 = db4.readData("SELECT sum(Buy_Detalis.Total) AS TotalSales FROM Buy_Detalis GROUP BY YEAR(CONVERT(date,[Buy_Detalis].[Date], 103)), MONTH(CONVERT(date,[Buy_Detalis].[Date], 103)) ORDER BY YEAR(CONVERT(date,[Buy_Detalis].[Date], 103)), MONTH(CONVERT(date,[Buy_Detalis].[Date], 103))", "");
        if (tblItems8.Rows.Count <= 0)
        {
            labelControl6.Text = "0.ج.م";
        }
        if (tblItems8.Rows.Count >= 1)
        {
            labelControl6.Text = (tblItems_40.Rows[0][2].ToString)();
            labelControl6.Text = Decimal.Parse(labelControl6.Text).ToString("C");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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