Как преобразовать varchar в datetime sql
Перейти к содержимому

Как преобразовать varchar в datetime sql

  • автор:

TablePlus

To convert a varchar string value to a datetime value using the CONVERT function in SQL Server, here is the general syntax:

That statement will convert the expression from varchar to datetime value using the specified style.

Here is the list of style values that you can use in the CONVERT statement:

Style Standard Output
100 Default for datetime and smalldatetime mon dd yyyy hh:miAM (or PM)
101 U.S. mm/dd/yyyy
102 ANSI yyyy.mm.dd
103 British/French dd/mm/yyyy
104 German dd.mm.yyyy
105 Italian dd-mm-yyyy
106 dd mon yyyy
107 Mon dd, yyyy
108 hh:mi:ss
109 Default + milliseconds mon dd yyyy hh:mi:ss:mmmAM (or PM)
110 USA mm-dd-yyyy
111 JAPAN yyyy/mm/dd
112 ISO yyyymmdd
113 Europe default + milliseconds dd mon yyyy hh:mi:ss:mmm(24h)
114 hh:mi:ss:mmm(24h)
120 ODBC canonical yyyy-mm-dd hh:mi:ss(24h)
121 ODBC canonical (with milliseconds) default for time, date, datetime2, and datetimeoffset yyyy-mm-dd hh:mi:ss.mmm(24h)
126 ISO8601 yyyy-mm-ddThh:mi:ss.mmm (no spaces)
130 Hijri dd mon yyyy hh:mi:ss:mmmAM
131 Hijra dd/mm/yyyy hh:mi:ss:mmmAM

You can also use the CAST function:

Example

With the style 101 (mm/dd/yyyy), the string value 09/10/2019 is now a datetime value.

Need a good GUI tool for databases? TablePlus provides a native client that allows you to access and manage Oracle, MySQL, SQL Server, PostgreSQL and many other databases simultaneously using an intuitive and powerful graphical interface.

Need a quick edit on the go? Download for iOS

Как преобразовать varchar в datetime sql

The BINARY operator converts the expression to a binary string (a string that has the binary character set and binary collation). A common use for BINARY is to force a character string comparison to be done byte by byte using numeric byte values rather than character by character. The BINARY operator also causes trailing spaces in comparisons to be significant. For information about the differences between the binary collation of the binary character set and the _bin collations of nonbinary character sets, see Section 10.8.5, “The binary Collation Compared to _bin Collations”.

The BINARY operator is deprecated as of MySQL 8.0.27, and you should expect its removal in a future version of MySQL. Use CAST(. AS BINARY) instead.

In a comparison, BINARY affects the entire operation; it can be given before either operand with the same result.

To convert a string expression to a binary string, these constructs are equivalent:

If a value is a string literal, it can be designated as a binary string without converting it by using the _binary character set introducer:

The BINARY operator in expressions differs in effect from the BINARY attribute in character column definitions. For a character column defined with the BINARY attribute, MySQL assigns the table default character set and the binary ( _bin ) collation of that character set. Every nonbinary character set has a _bin collation. For example, if the table default character set is utf8mb4 , these two column definitions are equivalent:

The use of CHARACTER SET binary in the definition of a CHAR , VARCHAR , or TEXT column causes the column to be treated as the corresponding binary string data type. For example, the following pairs of definitions are equivalent:

If BINARY is invoked from within the mysql client, binary strings display using hexadecimal notation, depending on the value of the —binary-as-hex . For more information about that option, see Section 4.5.1, “mysql — The MySQL Command-Line Client”.

timezone_specifier : [INTERVAL] ‘+00:00’ | ‘UTC’

With CAST( expr AS type syntax, the CAST() function takes an expression of any type and produces a result value of the specified type. This operation may also be expressed as CONVERT( expr , type ) , which is equivalent. If expr is NULL , CAST() returns NULL .

These type values are permitted:

Produces a string with the VARBINARY data type, except that when the expression expr is empty (zero length), the result type is BINARY(0) . If the optional length N is given, BINARY( N ) causes the cast to use no more than N bytes of the argument. Values shorter than N bytes are padded with 0x00 bytes to a length of N . If the optional length N is not given, MySQL calculates the maximum length from the expression. If the supplied or calculated length is greater than an internal threshold, the result type is BLOB . If the length is still too long, the result type is LONGBLOB .

For a description of how casting to BINARY affects comparisons, see Section 11.3.3, “The BINARY and VARBINARY Types”.

Produces a string with the VARCHAR data type, unless the expression expr is empty (zero length), in which case the result type is CHAR(0) . If the optional length N is given, CHAR( N ) causes the cast to use no more than N characters of the argument. No padding occurs for values shorter than N characters. If the optional length N is not given, MySQL calculates the maximum length from the expression. If the supplied or calculated length is greater than an internal threshold, the result type is TEXT . If the length is still too long, the result type is LONGTEXT .

With no charset_info clause, CHAR produces a string with the default character set. To specify the character set explicitly, these charset_info values are permitted:

CHARACTER SET charset_name : Produces a string with the given character set.

ASCII : Shorthand for CHARACTER SET latin1 .

UNICODE : Shorthand for CHARACTER SET ucs2 .

In all cases, the string has the character set default collation.

Produces a DATE value.

Produces a DATETIME value. If the optional M value is given, it specifies the fractional seconds precision.

Produces a DECIMAL value. If the optional M and D values are given, they specify the maximum number of digits (the precision) and the number of digits following the decimal point (the scale). If D is omitted, 0 is assumed. If M is omitted, 10 is assumed.

Produces a DOUBLE result. Added in MySQL 8.0.17.

If the precision p is not specified, produces a result of type FLOAT . If p is provided and 0 <= < p <= 24, the result is of type FLOAT . If 25 <= p <= 53, the result is of type DOUBLE . If p < 0 or p > 53, an error is returned. Added in MySQL 8.0.17.

Produces a JSON value. For details on the rules for conversion of values between JSON and other types, see Comparison and Ordering of JSON Values.

Like CHAR , but produces a string with the national character set. See Section 10.3.7, “The National Character Set”.

Unlike CHAR , NCHAR does not permit trailing character set information to be specified.

Produces a result of type REAL . This is actually FLOAT if the REAL_AS_FLOAT SQL mode is enabled; otherwise the result is of type DOUBLE .

Produces a signed BIGINT value.

As of MySQL 8.0.24, CAST() and CONVERT() support casting geometry values from one spatial type to another, for certain combinations of spatial types. For details, see Cast Operations on Spatial Types.

Produces a TIME value. If the optional M value is given, it specifies the fractional seconds precision.

Produces an unsigned BIGINT value.

Produces a YEAR value. Added in MySQL 8.0.22. These rules govern conversion to YEAR :

For a four-digit number in the range 1901-2155 inclusive, or for a string which can be interpreted as a four-digit number in this range, return the corresponding YEAR value.

For a number consisting of one or two digits, or for a string which can be interpreted as such a number, return a YEAR value as follows:

If the number is in the range 1-69 inclusive, add 2000 and return the sum.

If the number is in the range 70-99 inclusive, add 1900 and return the sum.

For a string which evaluates to 0, return 2000.

For the number 0, return 0.

For a DATE , DATETIME , or TIMESTAMP value, return the YEAR portion of the value. For a TIME value, return the current year.

If you do not specify the type of a TIME argument, you may get a different result from what you expect, as shown here:

If the argument is of type DECIMAL , DOUBLE , DECIMAL , or REAL , round the value to the nearest integer, then attempt to cast the value to YEAR using the rules for integer values, as shown here:

An argument of type GEOMETRY cannot be converted to YEAR .

For a value that cannot be successfully converted to YEAR , return NULL .

A string value containing non-numeric characters which must be truncated prior to conversion raises a warning, as shown here:

In MySQL 8.0.17 and higher, InnoDB allows the use of an additional ARRAY keyword for creating a multi-valued index on a JSON array as part of CREATE INDEX , CREATE TABLE , and ALTER TABLE statements. ARRAY is not supported except when used to create a multi-valued index in one of these statements, in which case it is required. The column being indexed must be a column of type JSON . With ARRAY , the type following the AS keyword may specify any of the types supported by CAST() , with the exceptions of BINARY , JSON , and YEAR . For syntax information and examples, as well as other relevant information, see Multi-Valued Indexes.

CONVERT() , unlike CAST() , does not support multi-valued index creation or the ARRAY keyword.

Beginning with MySQL 8.0.22, CAST() supports retrieval of a TIMESTAMP value as being in UTC, using the AT TIMEZONE operator. The only supported time zone is UTC; this can be specified as either of ‘+00:00’ or ‘UTC’ . The only return type supported by this syntax is DATETIME , with an optional precision specifier in the range of 0 to 6, inclusive.

TIMESTAMP values that use timezone offsets are also supported.

If you use ‘UTC’ as the time zone specifier with this form of CAST() , and the server raises an error such as Unknown or incorrect time zone: ‘UTC’ , you may need to install the MySQL time zone tables (see Populating the Time Zone Tables).

AT TIME ZONE does not support the ARRAY keyword, and is not supported by the CONVERT() function.

CONVERT( expr USING transcoding_name ) is standard SQL syntax. The non- USING form of CONVERT() is ODBC syntax. Regardless of the syntax used, the function returns NULL if expr is NULL .

CONVERT( expr USING transcoding_name ) converts data between different character sets. In MySQL, transcoding names are the same as the corresponding character set names. For example, this statement converts the string ‘abc’ in the default character set to the corresponding string in the utf8mb4 character set:

CONVERT( expr , type ) syntax (without USING ) takes an expression and a type value specifying a result type, and produces a result value of the specified type. This operation may also be expressed as CAST( expr AS type ) , which is equivalent. For more information, see the description of CAST() .

Prior to MySQL 8.0.28, this function sometimes allowed invalid conversions of BINARY values to a nonbinary character set. When CONVERT() was used as part of the expression for an indexed generated column, this could lead to index corruption following an upgrade from a previous version of MySQL. See SQL Changes, for information about how to handle this situation.

Character Set Conversions

CONVERT() with a USING clause converts data between character sets:

In MySQL, transcoding names are the same as the corresponding character set names.

To convert strings between character sets, you can also use CONVERT( expr , type ) syntax (without USING ), or CAST( expr AS type ) , which is equivalent:

If you specify CHARACTER SET charset_name as just shown, the character set and collation of the result are charset_name and the default collation of charset_name . If you omit CHARACTER SET charset_name , the character set and collation of the result are defined by the character_set_connection and collation_connection system variables that determine the default connection character set and collation (see Section 10.4, “Connection Character Sets and Collations”).

A COLLATE clause is not permitted within a CONVERT() or CAST() call, but you can apply it to the function result. For example, these are legal:

But these are illegal:

For string literals, another way to specify the character set is to use a character set introducer. _latin1 and _latin2 in the preceding example are instances of introducers. Unlike conversion functions such as CAST() , or CONVERT() , which convert a string from one character set to another, an introducer designates a string literal as having a particular character set, with no conversion involved. For more information, see Section 10.3.8, “Character Set Introducers”.

Character Set Conversions for String Comparisons

Normally, you cannot compare a BLOB value or other binary string in case-insensitive fashion because binary strings use the binary character set, which has no collation with the concept of lettercase. To perform a case-insensitive comparison, first use the CONVERT() or CAST() function to convert the value to a nonbinary string. Comparisons of the resulting string use its collation. For example, if the conversion result collation is not case-sensitive, a LIKE operation is not case-sensitive. That is true for the following operation because the default utf8mb4 collation ( utf8mb4_0900_ai_ci ) is not case-sensitive:

To specify a particular collation for the converted string, use a COLLATE clause following the CONVERT() call:

To use a different character set, substitute its name for utf8mb4 in the preceding statements (and similarly to use a different collation).

CONVERT() and CAST() can be used more generally for comparing strings represented in different character sets. For example, a comparison of these strings results in an error because they have different character sets:

Converting one of the strings to a character set compatible with the other enables the comparison to occur without error:

Character set conversion is also useful preceding lettercase conversion of binary strings. LOWER() and UPPER() are ineffective when applied directly to binary strings because the concept of lettercase does not apply. To perform lettercase conversion of a binary string, first convert it to a nonbinary string using a character set appropriate for the data stored in the string:

Be aware that if you apply BINARY , CAST() , or CONVERT() to an indexed column, MySQL may not be able to use the index efficiently.

Cast Operations on Spatial Types

As of MySQL 8.0.24, CAST() and CONVERT() support casting geometry values from one spatial type to another, for certain combinations of spatial types. The following list shows the permitted type combinations, where “ MySQL extension ” designates casts implemented in MySQL beyond those defined in the SQL/MM standard:

From LineString to:

Polygon (MySQL extension)

MultiPoint (MySQL extension)

From Polygon to:

LineString (MySQL extension)

MultiLineString (MySQL extension)

From MultiPoint to:

LineString (MySQL extension)

From MultiLineString to:

Polygon (MySQL extension)

MultiPolygon (MySQL extension)

From MultiPolygon to:

MultiLineString (MySQL extension)

From GeometryCollection to:

In spatial casts, GeometryCollection and GeomCollection are synonyms for the same result type.

Some conditions apply to all spatial type casts, and some conditions apply only when the cast result is to have a particular spatial type. For information about terms such as “ well-formed geometry, ” see Section 11.4.4, “Geometry Well-Formedness and Validity”.

General Conditions for Spatial Casts

These conditions apply to all spatial casts regardless of the result type:

The result of a cast is in the same SRS as that of the expression to cast.

Casting between spatial types does not change coordinate values or order.

If the expression to cast is NULL , the function result is NULL .

Casting to spatial types using the JSON_VALUE() function with a RETURNING clause specifying a spatial type is not permitted.

Casting to an ARRAY of spatial types is not permitted.

If the spatial type combination is permitted but the expression to cast is not a syntactically well-formed geometry, an ER_GIS_INVALID_DATA error occurs.

If the spatial type combination is permitted but the expression to cast is a syntactically well-formed geometry in an undefined spatial reference system (SRS), an ER_SRS_NOT_FOUND error occurs.

If the expression to cast has a geographic SRS but has a longitude or latitude that is out of range, an error occurs:

If a longitude value is not in the range (−180, 180], an ER_GEOMETRY_PARAM_LONGITUDE_OUT_OF_RANGE error occurs.

If a latitude value is not in the range [−90, 90], an ER_GEOMETRY_PARAM_LATITUDE_OUT_OF_RANGE error occurs.

Ranges shown are in degrees. If an SRS uses another unit, the range uses the corresponding values in its unit. The exact range limits deviate slightly due to floating-point arithmetic.

Conditions for Casts to Point

When the cast result type is Point , these conditions apply:

If the expression to cast is a well-formed geometry of type Point , the function result is that Point .

If the expression to cast is a well-formed geometry of type MultiPoint containing a single Point , the function result is that Point . If the expression contains more than one Point , an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type GeometryCollection containing only a single Point , the function result is that Point . If the expression is empty, contains more than one Point , or contains other geometry types, an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type other than Point , MultiPoint , GeometryCollection , an ER_INVALID_CAST_TO_GEOMETRY error occurs.

Conditions for Casts to LineString

When the cast result type is LineString , these conditions apply:

If the expression to cast is a well-formed geometry of type LineString , the function result is that LineString .

If the expression to cast is a well-formed geometry of type Polygon that has no inner rings, the function result is a LineString containing the points of the outer ring in the same order. If the expression has inner rings, an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type MultiPoint containing at least two points, the function result is a LineString containing the points of the MultiPoint in the order they appear in the expression. If the expression contains only one Point , an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type MultiLineString containing a single LineString , the function result is that LineString . If the expression contains more than one LineString , an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type GeometryCollection , containing only a single LineString , the function result is that LineString . If the expression is empty, contains more than one LineString , or contains other geometry types, an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type other than LineString , Polygon , MultiPoint , MultiLineString , or GeometryCollection , an ER_INVALID_CAST_TO_GEOMETRY error occurs.

Conditions for Casts to Polygon

When the cast result type is Polygon , these conditions apply:

If the expression to cast is a well-formed geometry of type LineString that is a ring (that is, the start and end points are the same), the function result is a Polygon with an outer ring consisting of the points of the LineString in the same order. If the expression is not a ring, an ER_INVALID_CAST_TO_GEOMETRY error occurs. If the ring is not in the correct order (the exterior ring must be counter-clockwise), an ER_INVALID_CAST_POLYGON_RING_DIRECTION error occurs.

If the expression to cast is a well-formed geometry of type Polygon , the function result is that Polygon .

If the expression to cast is a well-formed geometry of type MultiLineString where all elements are rings, the function result is a Polygon with the first LineString as outer ring and any additional LineString values as inner rings. If any element of the expression is not a ring, an ER_INVALID_CAST_TO_GEOMETRY error occurs. If any ring is not in the correct order (the exterior ring must be counter-clockwise, interior rings must be clockwise), an ER_INVALID_CAST_POLYGON_RING_DIRECTION error occurs.

If the expression to cast is a well-formed geometry of type MultiPolygon containing a single Polygon , the function result is that Polygon . If the expression contains more than one Polygon , an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type GeometryCollection containing only a single Polygon , the function result is that Polygon . If the expression is empty, contains more than one Polygon , or contains other geometry types, an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type other than LineString , Polygon , MultiLineString , MultiPolygon , or GeometryCollection , an ER_INVALID_CAST_TO_GEOMETRY error occurs.

Conditions for Casts to MultiPoint

When the cast result type is MultiPoint , these conditions apply:

If the expression to cast is a well-formed geometry of type Point , the function result is a MultiPoint containing that Point as its sole element.

If the expression to cast is a well-formed geometry of type LineString , the function result is a MultiPoint containing the points of the LineString in the same order.

If the expression to cast is a well-formed geometry of type MultiPoint , the function result is that MultiPoint .

If the expression to cast is a well-formed geometry of type GeometryCollection containing only points, the function result is a MultiPoint containing those points. If the GeometryCollection is empty or contains other geometry types, an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type other than Point , LineString , MultiPoint , or GeometryCollection , an ER_INVALID_CAST_TO_GEOMETRY error occurs.

Conditions for Casts to MultiLineString

When the cast result type is MultiLineString , these conditions apply:

If the expression to cast is a well-formed geometry of type LineString , the function result is a MultiLineString containing that LineString as its sole element.

If the expression to cast is a well-formed geometry of type Polygon , the function result is a MultiLineString containing the outer ring of the Polygon as its first element and any inner rings as additional elements in the order they appear in the expression.

If the expression to cast is a well-formed geometry of type MultiLineString , the function result is that MultiLineString .

If the expression to cast is a well-formed geometry of type MultiPolygon containing only polygons without inner rings, the function result is a MultiLineString containing the polygon rings in the order they appear in the expression. If the expression contains any polygons with inner rings, an ER_WRONG_PARAMETERS_TO_STORED_FCT error occurs.

If the expression to cast is a well-formed geometry of type GeometryCollection containing only linestrings, the function result is a MultiLineString containing those linestrings. If the expression is empty or contains other geometry types, an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type other than LineString , Polygon , MultiLineString , MultiPolygon , or GeometryCollection , an ER_INVALID_CAST_TO_GEOMETRY error occurs.

Conditions for Casts to MultiPolygon

When the cast result type is MultiPolygon , these conditions apply:

If the expression to cast is a well-formed geometry of type Polygon , the function result is a MultiPolygon containing the Polygon as its sole element.

If the expression to cast is a well-formed geometry of type MultiLineString where all elements are rings, the function result is a MultiPolygon containing a Polygon with only an outer ring for each element of the expression. If any element is not a ring, an ER_INVALID_CAST_TO_GEOMETRY error occurs. If any ring is not in the correct order (exterior ring must be counter-clockwise), an ER_INVALID_CAST_POLYGON_RING_DIRECTION error occurs.

If the expression to cast is a well-formed geometry of type MultiPolygon , the function result is that MultiPolygon .

If the expression to cast is a well-formed geometry of type GeometryCollection containing only polygons, the function result is a MultiPolygon containing those polygons. If the expression is empty or contains other geometry types, an ER_INVALID_CAST_TO_GEOMETRY error occurs.

If the expression to cast is a well-formed geometry of type other than Polygon , MultiLineString , MultiPolygon , or GeometryCollection , an ER_INVALID_CAST_TO_GEOMETRY error occurs.

Conditions for Casts to GeometryCollection

When the cast result type is GeometryCollection , these conditions apply:

GeometryCollection and GeomCollection are synonyms for the same result type.

If the expression to cast is a well-formed geometry of type Point , the function result is a GeometryCollection containing that Point as its sole element.

If the expression to cast is a well-formed geometry of type LineString , the function result is a GeometryCollection containing that LineString as its sole element.

If the expression to cast is a well-formed geometry of type Polygon , the function result is a GeometryCollection containing that Polygon as its sole element.

If the expression to cast is a well-formed geometry of type MultiPoint , the function result is a GeometryCollection containing the points in the order they appear in the expression.

If the expression to cast is a well-formed geometry of type MultiLineString , the function result is a GeometryCollection containing the linestrings in the order they appear in the expression.

If the expression to cast is a well-formed geometry of type MultiPolygon , the function result is a GeometryCollection containing the elements of the MultiPolygon in the order they appear in the expression.

If the expression to cast is a well-formed geometry of type GeometryCollection , the function result is that GeometryCollection .

Other Uses for Cast Operations

The cast functions are useful for creating a column with a specific type in a CREATE TABLE . SELECT statement:

The cast functions are useful for sorting ENUM columns in lexical order. Normally, sorting of ENUM columns occurs using the internal numeric values. Casting the values to CHAR results in a lexical sort:

CAST() also changes the result if you use it as part of a more complex expression such as CONCAT(‘Date: ‘,CAST(NOW() AS DATE)) .

For temporal values, there is little need to use CAST() to extract data in different formats. Instead, use a function such as EXTRACT() , DATE_FORMAT() , or TIME_FORMAT() . See Section 12.7, “Date and Time Functions”.

To cast a string to a number, it normally suffices to use the string value in numeric context:

That is also true for hexadecimal and bit literals, which are binary strings by default:

A string used in an arithmetic operation is converted to a floating-point number during expression evaluation.

A number used in string context is converted to a string:

For information about implicit conversion of numbers to strings, see Section 12.3, “Type Conversion in Expression Evaluation”.

MySQL supports arithmetic with both signed and unsigned 64-bit values. For numeric operators (such as + or — ) where one of the operands is an unsigned integer, the result is unsigned by default (see Section 12.6.1, “Arithmetic Operators”). To override this, use the SIGNED or UNSIGNED cast operator to cast a value to a signed or unsigned 64-bit integer, respectively.

If either operand is a floating-point value, the result is a floating-point value and is not affected by the preceding rule. (In this context, DECIMAL column values are regarded as floating-point values.)

The SQL mode affects the result of conversion operations (see Section 5.1.11, “Server SQL Modes”). Examples:

For conversion of a “ zero ” date string to a date, CONVERT() and CAST() return NULL and produce a warning when the NO_ZERO_DATE SQL mode is enabled.

For integer subtraction, if the NO_UNSIGNED_SUBTRACTION SQL mode is enabled, the subtraction result is signed even if any operand is unsigned.

SQL convert date

Daniel Calbimonte

A common task for newbies is to learn how to do a SQL convert date and work to convert them date to other data types or covert other data types to Date.

Here in this article we will explain how to work and convert dates to different formats or vice versa.

Requirements

  1. SQL Server installed. Starting in SQL Server 2008

Example

The first example will be simple, we have a varchar column with a date in a table, but we need to convert the varchar to date. We need to do a SQL convert date.

Here it is script to create the table with data:

We want to convert the column date from nvarchar(100) to a date.

To do it, we are going to try to modify the design of the table:

SSMS Design table

We will try to change the Data Type to smalldatetime:

change varchar to smalldatime in SSMS

You will receive the following error message:

Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.

To solve this error, in SSMS go to Tools > Options menu:

Change Options in SSMS

In Options, go to Designers >Table and Database Designers and uncheck the Prevent saving changes that require table re-creation:

Uncheck Prevent saving changes that require table re-creation

This option will disable to option to prevent saving table recreation. When you modify the column data type, it requires table re-creation.

Now, you can save the design and your table will be converted to date and the SQL convert date is completed:

SQL convert date: Date time results after convert sql date

Conversion functions

T-SQL contains functions to convert data types. We will use CAST and CONVERT to do a SQL convert date.

Let’s start with CAST first:

How to convert from varchar, nvarchar, char, nchar to sql date using CAST

The following example, will show how to convert characters to a datetime date type using the CAST function:

Convert varchar into datetime in SQL Server

How do I convert a string of format mmddyyyy into datetime in SQL Server 2008?

My target column is in DateTime

I have tried with Convert and most of the Date style values however I get an error message:

‘The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.’

ughai's user avatar

13 Answers 13

OP wants mmddyy and a plain convert will not work for that:

KM.'s user avatar

SQL Server can implicitly cast strings in the form of ‘YYYYMMDD’ to a datetime — all other strings must be explicitly cast. here are two quick code blocks which will do the conversion from the form you are talking about:

version 1 uses unit variables:

version 2 does not use unit variables:

Both cases rely on sql server’s ability to do that implicit conversion.

Likely you have bad data that cannot convert. Dates should never be stored in varchar becasue it will allow dates such as ASAP or 02/30/2009. Use the isdate() function on your data to find the records which can’t convert.

OK I tested with known good data and still got the message. You need to convert to a different format becasue it does not know if 12302009 is mmddyyyy or ddmmyyyy. The format of yyyymmdd is not ambiguous and SQL Server will convert it correctly

I got this to work:

You will still get an error message though if you have any that are in a non-standard format like ‘112009’ or some text value or a true out of range date.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *