简体   繁体   中英

Update table Error Using Convert Function In SQL Server 2005

I have a table with two columns, all of them are datetime value Such as, Column A with value '07/09/2012 14:13:34' Now, I want to update column A to yyyymmdd by statement

 Update Change_Date
    SET A = CONVERT(VARCHAR(8),A,112)

It shows succsessful message but with no effect (no update value to 20120907) in my table Change_Date.

Any help will be greated, thank you!

A datetime fields saves a date time. How you see that date time is a result of the tool you're using to inspect the data, whether it is Management Studio, or your own software that's printing something from the database.

I strongly recommend keeping it as a datetime field. This will allow you to do date-related operations, such as subtractions and comparisons. If you want to change how your users see the date, then format your date at the presentation layer.

What's happening in the code you've posted is that you're setting the value of A to the same date that it already is. The fact that you're setting that value by means of a string in another format has no relation, SQL server will always have to parse your string input into a date that it can understand. This is why you're not getting an error message. The operation is working, only it's not changing anything.

It's because the datatype of the column is DATE or DATETIME and it has specific format. If you want to update the column with specific format, make another column and make its datatype VARCHAR . I believe 112 is yyyymmdd format.

I strongly suggest that you keep it AS IS. Database is the storage of data and not for viewing purposes. It is easy to perform task for dates if your data type is DATETIME or DATE . If for instance you want to retrieve the dates with specific format, that's the time you convert your date.

Hope this makes sense.

在此处输入图片说明

您可以选择指定格式的日期列,或创建一个以yyyymmdd格式选择列值的视图:

SELECT CONVERT(VARCHAR(8), A, 112) FROM Change_Date

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