How to convert Datetime type to nvarchar?

Asked

Viewed 297 times

0

I have a table with a column like nvarchar, and I pass the following parameter to the stored Procedure:

cmd.Parameters.Add("@PointDate", SqlDbType.NVarChar).Value = DateTime.Now;

as predicted, I’m getting the following error:

Additional information: Error converting data type nvarchar to datetime.

How do I convert DateTime for nvarchar?

  • Must convert DateTime.Now for string

  • Why is your column Nvachar? Couldn’t it be varchar? Good to see you here in the OS.

  • And why do you want to convert Datetime to nvarchar? Why don’t you pass this parameter like this: cmd.Parameters.Add("@PointDate", SqlDbType.DateTime).Value = DateTime.Now;?

1 answer

0


Good. everything depends on how you will use this date as String in your SP.

Converting a date via Tostring will generate a string in the general long date format, whose end result varies according to the language settings of the machine where the function is rotated (unless the app manually changes the culture OR you use one of the Tostring overloads to specify another format). This can be problematic.

First of all, you need to find out what format this SP expects from this String.

1) If it will use the value to compare directly with a SQL datetime, then you will have problems. The best would be to instantiate a Sqldatetime passing as parameter its date, and then passing as parameter to SP the return of the Tosqlstring function();

var sqlDate = new SqlDateTime(DateTime.Now);
cmd.Parameters.Add("@PointDate", SqlDbType.NVarChar).Value = sqlDate.ToSqlString();

2) If it expects the date in a specific format (dd/MM/yyyy, or yyyy-mm-dd, etc.), then it is best to pass a Tostring(string format) with the required format. More information about Datetime formats in the MSDN.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.