convert int to smallint

  • Dear All,

    I have a field in the database which is small int since i only need to store numbers < 1000. In my code I am doing some calculations to get this value, and I am using a double datatype(so that I can use Math.Round) and then convert the number to an integer. Now I need to convert the int data type to smallint so that I can insert the value in the database. How can I do that?

  • 1.  CAST(Field AS SMALLINT)

    2. CONVERT(SMALLINT, Field)

    3.  Chop it up into small little bites, season liberally and bake at 350 F for 15 minutes.  Taste good with a red wine

     

    Happy New Year, everyone!



    Good Hunting!

    AJ Ahrens


    webmaster@kritter.net

  • AJ's method will work fine, although you might want a check to trap errors on the chance your int value exceeds the max smallint value.

  • I agree with Steve... trap for errors if you are goin to build your own T-SQL to do this.  If you use Enterprise Manager to make the table design change, you don't have to worry about that... the underlying code it builds to make the change is air-tight.

    --Jeff Moden

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • I am using the Enterprise Manager to build the database. Basically I want to store image's width and height in these fields, so a value of less than 2000 will normally be the case. If I use int instead of smallint, will it have a big performance drawback on the database?

  • It sounds to me that SMALLINT would be the most appropriate here but, if you use INT instead, you will not notice a huge performance change.  The big drawback of using INT over SMALLINT is that INT takes twice as many bytes as SMALLINT.  It's always my goal to use the most appropriate size field for the sake of shorter backups.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • ok Jeff, thanks very much for your help

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply