CAST (original_expression AS desired_datatype) : Cast « Data Type « SQL Server / T-SQL






CAST (original_expression AS desired_datatype)

 


6> CREATE TABLE employee
7> (
8>    emp_id         varchar(20),
9>    fname          varchar(20)       NOT NULL,
10>    minit          char(1)               NULL,
11>    lname          varchar(30)       NOT NULL,
12>    job_id         smallint          NOT NULL       DEFAULT 1,
13>    job_lvl        tinyint                          DEFAULT 10,
14>    pub_id         char(4)           NOT NULL       DEFAULT ('9952'),
15>    hire_date      datetime          NOT NULL       DEFAULT (getdate())
16> )
17> GO
1>
2> insert employee values ('1', 'Jack', 'T', 'Lee',     2, 215, '9952', '11/11/89')
3> insert employee values ('2', 'Jode', 'M', 'Devon',   3, 200, '9952', '07/16/91')
4> insert employee values ('3', 'Frac', 'F', 'Chang',   4, 227, '9952', '11/03/90')
5> insert employee values ('4', 'Like', 'A', 'Lebihan', 5, 175, '0736', '06/03/90')
6> insert employee values ('5', 'Paul', 'X', 'Henriot', 5, 159, '0877', '08/19/93')
7> insert employee values ('6', 'Sick', 'K', 'Ottlieb', 5, 150, '1389', '04/05/91')
8> insert employee values ('7', 'Rita', 'B', 'Muller',  5, 198, '1622', '10/09/93')
9> insert employee values ('8', 'Mary', 'J', 'Pontes',  5, 246, '1756', '03/01/89')
10> insert employee values ('9', 'Jane', 'Y', 'Labrune', 5, 172, '9901', '05/26/91')
11> insert employee values ('10','Carl', 'F', 'Hernadez',5, 211, '9999', '04/21/89')
12> GO

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)
1>
2>
3> SELECT lname + '-' + CAST(job_id AS varchar(2)) FROM employee
4> GO

---------------------------------
Lee-2
Devon-3
Chang-4
Lebihan-5
Henriot-5
Ottlieb-5
Muller-5
Pontes-5
Labrune-5
Hernadez-5

(10 rows affected)
1>
2> drop table employee;
3> GO

 








Related examples in the same category

1.CAST(expression AS data type(<length>))
2.CAST(2.78128 AS integer)
3.CAST(2.78128 AS money)
4.CAST('11/11/72' as smalldatetime) AS '11/11/72'
5.select CAST('2002-09-30 11:35:00' AS smalldatetime) + 1 (plus)
6.select CAST('2002-09-30 11:35:00' AS smalldatetime) - 1 (minus)
7.select CAST(CAST('2002-09-30' AS datetime) - CAST('2001-12-01' AS datetime) AS int)
8.The CAST() function accepts one argument, an expression
9.Mixing Datatypes: CAST and CONVERT
10.Cast date type to char
11.CAST can still do date conversion
12.Cast date to different format
13.Cast number to varchar and use the regular expressions
14.Conversion with CONVERT function for computated value with numbers in list
15.Cast int to decimal
16.Convert varchar to number
17.CONVERT() does the same thing as the CAST() function
18.CAST(ID AS VarChar(5))
19.CAST('123.4' AS Decimal)
20.Arithmetic overflow error converting numeric to data type varchar.