
Now use the above style in the following query: select convert(varchar(20),GETDATE(),108)Įxample 6: In this example we use the style value 107 which defines the following format: Set as int) + as int) +CAST as int) as ResultĮxample 5: In this example we take a style value 108 which defines the following format: There are many style formats you can use. The numbers shown in red are the style formatter. SELECT CONVERT(VARCHAR,GETDATE(),101) as MMDDYYYY,ĬONVERT(VARCHAR,GETDATE(),111) as YYYYMMDD If not, read Data Type Conversion Functions on my site to learn everything.Įxample 2: You can define the format of the resulting date, such as YYYY/MM/DD or MM/DD/YYYY, when converting a DateTime datatype to Varchar.
#RAZORSQL CAST FUNCTION HOW TO#
This example should help you remember how to use the CAST and CONVERT functions. In both instances, we are translating from the text value "10" to its integer equivalent.

Add 100 to a style value to get a four-place year that includes the century (yyyy).Įxample 1: Here is an example using both functions in the same statement: SELECT CAST ('10' as int) * 20, Style - style values for datetime or smalldatetime conversion to character data. Syntax: CONVERT(data_type(length), expression, style) The source type is determined by the data type of the expression you are casting from. Target type refers to the data type that you are casting an expression to. You can use the CONVERT () function to display date / time data in a variety of formats.ĬONVERT differs in that it accepts optional style parameters used for formatting. For such things, conversion functions are used. In many cases, to convert an expression from one type to another, you need to convert the data from a datetime type to a varchar type in a stored procedure or other routine.

The Cast () function provides a data type for dynamic parameters (?) Or null values. There is no performance degradation when using CAST. Therefore, it is suitable for use in other database implementations.The Cast () function is used to convert a data type variable or data from one data type to another.

