Conversion failed when converting datetime from ch

2019-07-26 15:57发布

问题:

I am trying to pass parameters from windows application to a stored procedure. there are two parameters '@dt' & '@dt2' which get value from datetimepickers. whenever i execute the stored procedure it comes up with the error saying "Conversion failed when converting datetime from character string."

After executing the query i want to display it in a datagridview.

i am unable to figure out the problem.. here is my procedure and code

Stored Procedure

ALTER proc [dbo].[deepak_proc]

( @dt datetime, @dt2 datetime )

AS

declare @cols AS NVARCHAR(MAX)

declare @query AS NVARCHAR(MAX)

select @cols =

              STUFF((SELECT ',' + QUOTENAME(date +'_'+Logname) 
                from
                (
                  select K_date,
                    convert(char(10),K_date, 101) date, 
                    LogName
                  from kq_report_analyze
                  cross apply
                  (
                    select 'In' LogName
                    union all
                    select 'Out' 
                  ) l
                ) s   
                group by convert(char(10), K_date, 112), date, Logname
                order by convert(char(10), K_date, 112)
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

set @query

= 'SELECT empid, name, status, '+@cols+' FROM (SELECT empid, name, status, 
   doortime, date + "_" + col AS col_names FROM  (SELECT k_userid
   AS [empid], K_Name AS name, k_description1 as [status], K_WorktimeUp1
   AS [IN], K_WorktimeDown1 AS OUT, CONVERT(char(10), K_Date, 101) AS
  date FROM  dbo.kq_report_analyze WHERE (K_Date BETWEEN '+@dt+' AND
  '+@dt2+') GROUP BY K_UserID, K_Name, k_description1, K_Date,
  K_WorktimeUp1, K_WorktimeDown1) src  UNPIVOT (doortime FOR col IN
  ([IN], [OUT])) unpiv) 
  p PIVOT (max(doortime) FOR col_names IN ('+@cols+')) piv;'

execute(@query)

And the following code is on button click

SqlConnection con = new SqlConnection(); con.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=test_db;User ID=user;Password=password";

     con.Open();


       SqlCommand cmd = new SqlCommand("deepak_proc", con);


   cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add("@dt", SqlDbType.DateTime).Value = dateTimePicker1.Value.ToString("MM/dd/yyyy");

cmd.Parameters.Add("@dt2", SqlDbType.DateTime).Value = dateTimePicker2.Value.ToString("MM/dd/yyyy");

DataTable dt = new DataTable();

cmd.ExecuteNonQuery();

sda.Fill(dt);

dataGridView1.DataSource = dt;

con.Close();

回答1:

Use sp_executesql system stored procedure and put your variables as parametrs

SET @query
= 'SELECT empid, name, status, ' + @cols + ' 
   FROM (SELECT empid, name, status, doortime, date + ''_'' + col AS col_names 
         FROM  (SELECT k_userid AS [empid], K_Name AS name, 
                       k_description1 as [status], K_WorktimeUp1 AS [IN], 
                       ktimeDown1 AS OUT, CONVERT(char(10), K_Date, 101) AS date 
                FROM  dbo.kq_report_analyze 
                WHERE (K_Date BETWEEN @dt AND @dt2) 
                GROUP BY K_UserID, K_Name, k_description1, K_Date, K_WorktimeUp1,
                         K_WorktimeDown1) src  
   UNPIVOT (doortime FOR col IN ([IN], [OUT])) unpiv) p 
   PIVOT (max(doortime) FOR col_names IN (' + @cols + ')) piv;'

EXEC sp_executesql @query, N'@dt datetime, @dt2 datetime', @dt, @dt2


回答2:

Try to pass the datetime into the yyyy-MM-dd format which is standard.



回答3:

Sounds as though you're getting a string representation of a date from the DateTimepicker in the client. When you get the value from the DateTimepicker, convert it to a bona fide CLR Date object client-side. Don't pass strings to the back-end if there is a CLR type that maps to the SQL type. Choose the appropriate parameter type when building the command object client-side.

In general, keep dates as dates and convert them to strings only when you need to display them for human eyes.

Edit: For example:

        SqlClient.SqlParameter  p0;

        p0.ParameterName = "@startdate";
        p0.SqlDbType = SqlDbType.DateTime;
        p0.Value =  < a datetime object, not a string>  
        p0.Direction = ParameterDirection.Input;

Then add the parameter to the Parameters collection.



回答4:

DateTime myDateTime = Convert.ToDateTime(dateTimePicker1.Value);

cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter
("@myDateTime", MySql.Data.MySqlClient.MySqlDbType.DateTime));
 cmd.Parameters["@myDateTime"].Value = myDateTime;


回答5:

cmd.Parameters.Add("@dt", SqlDbType.DateTime).Value =DateTime.ParseExact( dateTimePicker1.Value.Tostring(),null);

cmd.Parameters.Add("@dt2", SqlDbType.DateTime).Value =DateTime.ParseExact(dateTimePicker2.Value.Tostring(),null);