Siva
Siva

Reputation: 25

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

This is the Winforms C# code:

dateTimePicker3.Format = DateTimePickerFormat.Custom;
dateTimePicker3.CustomFormat = "dd-MM-yyyy";
dateTimePicker4.Format = DateTimePickerFormat.Custom;
dateTimePicker4.CustomFormat = "dd-MM-yyyy";

string connectionstring = @"Data Source=.;Initial Catalog=ExpenseManagerDB;Integrated Security=True";

SqlConnection sqlconn = new SqlConnection(connectionstring);
sqlconn.Open();

string query = @"sp_Total";
SqlCommand cmd = new SqlCommand(query, sqlconn);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add("@date1", dateTimePicker3.Value);
cmd.Parameters.Add("@date2", dateTimePicker4.Value);

SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();

Stored procedure follows:

Alter PROCEDURE sp_Total @date1 date,@date2 date

AS
BEGIN

Select SUM(Price) from EntryDetails where Name = 'Sreejith' and Date between '@date1' and '@date2'
Select SUM(Price) from EntryDetails where Name = 'Siva' and Date between '@date1' and '@date2'
Select SUM(Price) from EntryDetails where Name = 'Pavithran' and Date between '@date1' and '@date2'
Select SUM(Price) from EntryDetails where Name = 'Nithin' and Date between '@date1' and '@date2'

END
GO

I'm getting this error Conversion failed when converting date and/or time from character string

Upvotes: 0

Views: 328

Answers (2)

ASh
ASh

Reputation: 35720

it is not winforms, it is sql error

'@date1' and '@date2' are not dates but strings

remove '' in stored procedure

Alter PROCEDURE sp_Total @date1 date,@date2 date

AS
BEGIN
Select SUM(Price) from EntryDetails where Name = 'Sreejith' and Date between @date1 and @date2
Select SUM(Price) from EntryDetails where Name = 'Siva' and Date between @date1 and @date2
Select SUM(Price) from EntryDetails where Name = 'Pavithran' and Date between @date1 and @date2
Select SUM(Price) from EntryDetails where Name = 'Nithin' and Date between @date1 and @date2
END

UPDATE

Alter PROCEDURE sp_Total @date1 date, @date2 date

AS
BEGIN
  Select Name, SUM(Price) as SumPrice
  from EntryDetails 
  where 
    (Date between @date1 and @date2)
    and Name in ('Sreejith','Siva','Pavithran','Nithin')
  group by Name
END

Upvotes: 1

Anurag
Anurag

Reputation: 572

You need to pass @date1 and @date2 as Date types to the procedure, because the procedure takes in 2 params of type Date.

Hence in your code, you can change something as below:

    cmd.Parameters.Add("@date1", dateTimePicker3.Value.Date);
    cmd.Parameters.Add("@date2", dateTimePicker4.Value.Date);

Try it, let us know if you face any further problems.

Upvotes: 0

Related Questions