Use of cast function and types which are allowed?

804    Asked by IanRobertson in SQL Server , Asked on Nov 1, 2019
Answered by Ian Robertson

Cast is the function which is used to convert from one format to another. Example: Cast (data_variable, datetype).

Below table tell us the combination of data types which can be converted.

Datatype1 is converted to other datatype2, but it is not necessary that datatype2 can be converted into datatype1.



BOOLEAN

INTEGER

BIGINT

DECIMAL

FLOAT

CHAR

VAR

CHAR

DATE

TIME

TIME

STAMP

BOOLEAN

Y

-

-

-

-

Y

Y

-

-

-

INTEGER

-

Y

Y

Y

Y

Y

-

-

-

-

BIGINT

-

Y

Y

Y

Y

Y

-

-

-

-

DECIMAL

-

Y

Y

Y

Y

Y

-

-

-

-

FLOAT

-

Y

Y

Y

Y

-

-

-

-

-

CHAR

Y

Y

Y

Y

-

Y

Y

Y

Y

Y

VARCHAR

Y

Y

Y

Y

-

Y

Y

Y

Y

Y

DATE

-

-

-

-

-

Y

Y

Y

-

-

TIME

-

-

-

-

-

Y

Y

-

Y

-

TIMESTAMP

-

-

-

-

-

Y

Y

Y

Y

Y

Eg. You can convert decimal to varchar but all varchar data can’t be converted into decimal

declare @data decimal(10,2)

set @data=10.3

select Cast (@data as VARCHAR(40))

output: 10.3

declare @data1 VARCHAR(10)

set @data1=10.3

select Cast (@data1 as decimal(10,1))

output: 10.3


declare @data1 VARCHAR(10)

set @data1='abc'

select Cast (@data1 as decimal(10,1))

output: Error converting data type varchar to numeric.

Cast is the function which is used to convert from one format to another. Example: Cast (data_variable, datetype).

Below table tell us the combination of data types which can be converted.

Datatype1 is converted to other datatype2, but it is not necessary that datatype2 can be converted into datatype1.



BOOLEAN

INTEGER

BIGINT

DECIMAL

FLOAT

CHAR

VAR

CHAR

DATE

TIME

TIME

STAMP

BOOLEAN

Y

-

-

-

-

Y

Y

-

-

-

INTEGER

-

Y

Y

Y

Y

Y

-

-

-

-

BIGINT

-

Y

Y

Y

Y

Y

-

-

-

-

DECIMAL

-

Y

Y

Y

Y

Y

-

-

-

-

FLOAT

-

Y

Y

Y

Y

-

-

-

-

-

CHAR

Y

Y

Y

Y

-

Y

Y

Y

Y

Y

VARCHAR

Y

Y

Y

Y

-

Y

Y

Y

Y

Y

DATE

-

-

-

-

-

Y

Y

Y

-

-

TIME

-

-

-

-

-

Y

Y

-

Y

-

TIMESTAMP

-

-

-

-

-

Y

Y

Y

Y

Y

Eg. You can convert decimal to varchar but all varchar data can’t be converted into decimal

declare @data decimal(10,2)

set @data=10.3

select Cast (@data as VARCHAR(40))

output: 10.3

declare @data1 VARCHAR(10)

set @data1=10.3

select Cast (@data1 as decimal(10,1))

output: 10.3


declare @data1 VARCHAR(10)

set @data1='abc'

select Cast (@data1 as decimal(10,1))

output: Error converting data type varchar to numeric.



Your Answer

Interviews

Parent Categories