Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get right n digits from number in SQL Server (CE)

Tags:

c#

sql

sql-server

I have a sql server compact framework database and I want to query an int column

the column can contain values from 1 to 99999999 and I am interested in the right 4 digits

Examples:

     1 ->    1
    12 ->   12
   123 ->  123
  1234 -> 1234
 12345 -> 2345
123456 -> 3456

I could convert the result to string and use substring, but there is propably a better solution.

like image 419
Jürgen Steinblock Avatar asked Nov 08 '13 08:11

Jürgen Steinblock


People also ask

How do I find the number of digits in SQL?

SQL Server LEN() Function The LEN() function returns the length of a string. Note: Trailing spaces at the end of the string is not included when calculating the length. However, leading spaces at the start of the string is included when calculating the length.

How do I select the first 4 characters in SQL?

SQL Server LEFT() Function The LEFT() function extracts a number of characters from a string (starting from left).


2 Answers

Use Modulo

 select 123456 % 10000

SQLFiddle demo

like image 191
juergen d Avatar answered Nov 11 '22 08:11

juergen d


If you

SELECT WhateverField % 10000

you will get the 4 rightmost digits.

like image 37
Roy Dictus Avatar answered Nov 11 '22 10:11

Roy Dictus