T-SQL Tutorial

How to convert Varchar to INT


To convert a Varchar to INT uses sql conversion functions like cast or convert.

Syntax

CAST ( expression AS datatype [ ( length ) ] )

CONVERT ( datatype [ ( length ) ] , expression [ , style ] )





Examples

The examples below shows the conversion of a string to the int type.
A varchar variable and an int variable are declared, then the value of the varchar variable is set. It converts varchar to int type with the help of cast and convert functions.
The varchar variable must contain numeric characters.

USE tempdb;
GO
DECLARE @varchar AS varchar(100);
DECLARE @int AS int;
SET @varchar = '111223';
SET @int = CAST(@varchar AS INT);
PRINT @int;
SET @varchar = '44123';
SET @int = CONVERT(INT, @varchar);
PRINT @int;
GO

SELECT CAST('77788' AS INT);

SELECT CAST(CAST ('888.67' AS NUMERIC) AS INT);
SELECT CAST(CAST ('888.6789' AS NUMERIC(19,4)) AS INT);

SELECT CONVERT(INT, '888');
SELECT CONVERT(INT, CONVERT(NUMERIC, '888.45'));
SELECT CONVERT(INT, CONVERT(NUMERIC(19,4), '888.45'));