question

Rahul_Gautam avatar image
Rahul_Gautam asked

I am creating a function to check that the provided number is either even or odd?

I have created a function to check that the provided number is either even or odd?

But when I run the function it is giving below error.

"

Msg 245, Level 16, State 1, Line 101

Conversion failed when converting the varchar value ' No is Odd' to data type int."

I know error occurs because of different data types. Please assist.

Used below code.

Create function fn_tocheckodd_even

(@Number int)

returns int

as

begin

Declare @Num int


Set @Num= (Select

Case

when @Number%2=0

then 'No is Even'

else

' No is Odd' end as Q1)

return @Num

end

But if use number 1 instead of 'No is Even ' and Number 2 instead of 'No is odd', then the function works.


user-defined-function
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
anthony.green avatar image
anthony.green answered

All about your return type, you have declared @Num as INT not as VARCHAR

"No is Even" / "No is Odd" are strings and will not convert to INTs

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.