How do I convert an integer to tinyint within my VB.NET code?

I'm trying to run an INSERT statement, but I need to convert a regular integer to a tinyint.
How do I do that?


I tried using CAST(# as tinyint), but I receive an error.
winterhowlAsked:
Who is Participating?
 
LowfatspreadCommented:
as long as the value is less than 256 you shouldn't need to convert SQL will do that automatically...

if the number is > 255 then your logic has an error..
0
 
Anthony PerkinsCommented:
>>I tried using CAST(# as tinyint), but I receive an error.<<
You will get an error if the integer is greater than 256.
0
 
Anthony PerkinsCommented:
Actually that should have read greater than 255 and the error is:
Arithmetic overflow error for data type tinyint, value = 256.

If you do not care what value is inserted when greater than 255, you can do something like this:
CAST(YourIntegerValue % 256 As tinyint)
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
winterhowlAuthor Commented:
Actually, I was trying to convert 0 when I received the error.
0
 
Anthony PerkinsCommented:
Works fine for me:

Declare @X integer, @Y tinyint
Set @X = 0
Set @Y = CAST(@X as tinyint)
Select @Y

0
 
winterhowlAuthor Commented:
I couldn't get any of the CONVERT or CAST to work, but once I removed them, everything works fine.
0
 
Anthony PerkinsCommented:
>>I couldn't get any of the CONVERT or CAST to work<<
You do of course realize that CONVERT and CAST are T-SQL functions and not VB.NET functions, right?
0
 
winterhowlAuthor Commented:
Yes.  I was using them in the SQL I was using to get data from our database.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.