Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i have table that contain A text field [nvarchar(10)]

how to convert this field to date ?

when i try to change in the field in the design mode - i get this:

Unable to modify table.

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

is there any query that i can run to do it ?

thank's in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
291 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could to follow this steps:

  • Create a new datetime column, nullable
  • Update that column with properly casted values
  • Drop your original column
  • Rename and adjust your column to do not accept nulls, if applicable

Try this sample:

CREATE TABLE #Sample
(
    FieldAsText varchar(10) NOT NULL
);
GO

INSERT INTO #Sample VALUES ('2009-01-24');

ALTER TABLE #Sample ADD FieldAsDate datetime NULL
GO

UPDATE #Sample SET FieldAsDate = CONVERT(DATETIME, FieldAsText)

SELECT * FROM #Sample 

ALTER TABLE #Sample DROP COLUMN FieldAsText
ALTER TABLE #Sample ALTER COLUMN FieldAsDate datetime NOT NULL
GO

SELECT * FROM #Sample 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...