Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

data type mismatch

1 view
Skip to first unread message

Neha Bansal

unread,
Jan 22, 2010, 7:40:01 AM1/22/10
to
sir/madam,
i have two parameters , one for int and one for varchar. In print statement
i wrote as
PRINT 12 + '12' then it gives 24 as result, but when i give 12 + 'neha' it
gives me an error i.e. varchar can not be converted to integer. plz give me
the solution.

Hugo Kornelis

unread,
Jan 24, 2010, 6:19:56 AM1/24/10
to

Hi Neha,

What do you expect as anwer from SELECT 12 + 'neha'? I am unable to add
a string to the number 12 and get a meaningful result.

SQL Server uses rules for data conversion. Integer has higer precedence
than varchar, so it will attempt to convert the string to integer and
then add the values. So SELECT 12 + '12' is equivalent to SELECT 12 +
CAST('12' AS int), which works out to 12 + 12, or 24. Your description
sounds as if this is what you expected.

Applying the same rule to 12 + 'neha' leads to SELECT 12 + CAST('neha'
AS int), which will of course fail.

If you want to override the default conversions, you have to add
explicit CAST functions to modify the datatype yourself:
SELECT CAST(12 AS varchar(5)) + '12'; ==> '1212'
SELECT CAST(12 AS varchar(5)) + 'neha'; ==> '12neha'

--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis

0 new messages