SQL: how to get the left 3 numbers from an int - sql

I want to retrieve the left 3 numbers from an integer to be stored in a table. For example, if the int is 1234567, I want to retrieve 123. I want the second number (123) to also be an int; I don't want to convert anything to a string.
(And yes, really I should be working with strings. But I don't have control over that aspect of the issue.)
Thank you!

For SQL Server, the easiest way would definitely be:
SELECT CAST(LEFT(CAST(YourInt AS VARCHAR(100)), 3) AS INT)
Convert to string, take the left most three characters, and convert those back to an INT.
Doing it purely on the numerical value gets messy since you need to know how many digits you need to get rid of and so forth...
If you want to use purely only INT's, you'd have to construct something like this (at least you could do this in SQL Server - I'm not familiar enough with Access to know if that'll work in the Access SQL "dialect"):
DECLARE #MyInt INT = 1234567
SELECT
CASE
WHEN #MyInt < 1000 THEN #MyInt
WHEN #MyInt > 10000000 THEN #MyInt / 100000
WHEN #MyInt > 1000000 THEN #MyInt / 10000
WHEN #MyInt > 100000 THEN #MyInt / 1000
WHEN #MyInt > 10000 THEN #MyInt / 100
WHEN #MyInt > 1000 THEN #MyInt / 10
END AS 'NewInt'
But that's always an approximation - what if you have a really really really large number..... it might just fall through the cracks....

Without casting to string, how about this?
(T-SQL)
select #i / power(10,floor(log10(#i))-2)
Throws an error if the int is less than 100, but seems to work otherwise.
EDIT: To handle the error gracefully, you'd have to use a CASE since TSQL has no GREATEST() function...
select #i / case when #i < 100 then 1 else power(10,floor(log10(#i))-2) end

In access SELECT clng(left(cstr(field), 3)) FROM T should work.
Edit: Infact I bet it wont care about the cstr().

;WITH c10 AS
(
SELECT
Number
FROM
MyTable --?? WHERE Number>=1000
UNION ALL
SELECT Number/10 FROM c10 WHERE Number>=1000
)
SELECT Number FROM c10 WHERE Number < 1000
I can't test this, but it should do the trick. Iterate through until you end up with < 1000, relying on integer division. You may need to filter on the first clause to fine tune it
For a raw TSQL SQL Server 2005 solution only

well if you have access to php you could use substr
echo substr('1234567', 0, 3); and then convert the string back to an int
Converting an integer to a string in PHP
good luck!

Related

Find next greater number with zeros in sql number

I'm looking for a way to find next greater number starting by 1 and followed by zeros in Microsoft SQL. Numbers could vary in digits. ie:
Query: 9856, Result after procedure: 10000
Query: 98999, Result after procedure: 100000
Thanks.
EDIT: There is no chance of having negative numbers. This is a calculation for a energy meter. For example, numbers can go up to 99999 or 999999 or 9999999. When energy overcome that number, it will start again at 0. So I can't read what energy has been used in that period. To know it, I need to calculate the number as asked, then perform some basic maths.
There is no need for knowing what is going on on 10, 100, etc, because of the nature of the operation. It will only be used when the above escenario happend.
I don't know why you require or mathematically any other formula can be implemented. but technically that can be achieved as follows
DECLARE #count INT
SET #count = 1000
DECLARE #result INT
SET #result = CASE WHEN #count%10 = 0 THEN #count ELSE CAST('1'+REPLICATE('0',LEN(#count)) AS INT) end
SELECT #result
This works for positive numbers (numbers greater than zero):
select power(10, ceiling( log10(the_number) )) from mytable;
In case the number is already a power of ten (1, 10, 100, ...) , the number itself is returned.
You can do this with just arithmetic operations:
select power(10, floor(log(v.n - 0.1, 10)) + 1)
from (values (1), (10), (8), (9982), (124)) v(n)
This is a fairly crude way of doing it, however it does work. The query basically looks at the number of digits your number has, assumes the next integer you want starts with a 1 and then adds the relevant number of 0's to it.
Note this only looks for the next increment and does not round down.
Also for 10 you will get 100 and for 1000 you will get 10000.
declare #number int = 98999;
declare #len int = len(#number);
declare #stringtoreturn nvarchar(200)='1';
declare #runs int = 1;
while #runs<=#len
begin
select #stringtoreturn = #stringtoreturn + '0';
select #runs=#runs+1;
end
select #stringtoreturn;

truncate integer

I got a task to chop an integer by 1 digit.
For example, If the new limit is 3 digits then 1234 will become 999 after the change. if the before change value is 12345 then it should becomes 999 after changes. if the pre-change value is 564 then it will remain unchanged.
This has to be done on Oracle as well as SQL server. the truc function only truncates decimal but not integer.
What is the best way to do this in SQL, PL/SQL or T-SQL?
Thanks in advance.
This works for T-SQL. Converting it to other sql dialects should just be as simple as finding the similar methods
declare #numDigits INT = 3;
declare #maxNumber INT = POWER(10,#numDigits)-1 -- gets "999" when using 3 digits, 9999 when using 4 etc
DECLARE #input INT = 1234
DECLARE #output INT = IIF(#input>#maxNumber,#maxNumber,#input)
SELECT #output -- selects 999
Oracle does have the POWER function, but does not have the ternary/IIF function
You could use case statements for this like:
SELECT CASE [yourInt] >= 1000 THEN 999 ELSE [yourInt] END AS 'UpperLimit'
From [YouTable]

Pad a number with zeros, but only if it's below a certain length?

I have numbers that must be at least 7 digits long. For example:
0000001
123456789
0012345
Are all valid. I only need to pad the number with 0's only if its length is below 7. How do I do this in SQL Server? The best I've been able to get is to pad the number if the length is less than 7, but above that, it starts to truncate the number instead.
SELECT CASE WHEN LEN(CONVERT(VARCHAR(12), column)) > 7 THEN
CONVERT(VARCHAR(12),column) ELSE
RIGHT('0000000' + CONVERT(VARCHAR(12), column), 7) END
FROM dbo.table;
Aaron Bertrand beat me to it.
I'd like to add that it might also be useful to encapsulate both the character and number of times you have to repeat it, so that if it needs to change sometime in the future, it's easy to do it. You can do this using REPLICATE. So expanding on Aaron's example:
DECLARE #num_digits as int = 7
SELECT RIGHT(REPLICATE('0', #num_digits) + col, #num_digits) FROM dbo.table;
Hi check this out.
declare #num table(num varchar(10))
insert into #num
VALUES('0000001'),('123456789'),('0012345'),('123'),('11')
select CASE when len(num) < 7 then REPLICATE('0',(7-len(num)))+num else num END from #num

How to Implement Excel COMBIN function in SQL

How can i implement Excel COMBIN function in SQL 2005, either in a store procedure or in a function. About COMBIN function in Excel follow this Link.
Thanks.
Either implement a factorial function or depending on your possible input range, store factorial results in a table.
Implement the formula, as seen in your link.
No built-in method for doing this, you will have to make a custom user-defined function.
Rather than doing something crazy like a recursively factorial (as seen in this forum discussion), I would do the following:
Create a factorial lookup table, holding pre-calculated factorial values (maybe 1! to 100!, since 100! is over 9.3 × 10^157), or as high as you think you might need.
Then in your user-defined function, just look up n!, k!, and (n-k)! from the table, then calculate (n!) / (k!) * (n-k)!
Depending on what your possible input values are going to be, it may be worth pre-computing the values and storing them in a table; retrieving COMBIN(n, k) would then be as easy as
SELECT value FROM Combin WHERE n = #n AND k = #k
Precalculation does seem more sensible but a solution without.
declare #n int
declare #k int
SET #n = 8
SET #k = 2
SELECT
POWER(10.0, SUM(CASE WHEN Number > (#n - #k) THEN LOG10(Number) ELSE 0 END))/
POWER(10.0, SUM(CASE WHEN Number <= #k THEN LOG10(Number) ELSE 0 END))
FROM master.dbo.spt_values
WHERE type='P' AND
((Number > 0 and Number <= #k) OR (Number > (#n - #k) AND Number <= #n))

Splitting decimal in sql

I am getting result as decimal in stored procedure. If I am getting result as 123.45,
I want to split it into 123 and 45. Can anybody help?
use SQL function FLOOR() for getting integer part
and subtract that from the original for the decimal part
You can also make use of ROUND instead of FLOOR.
See section C. Using ROUND to truncate for trucate, and then subtract that from the original.
Be aware that using FLOOR on negative numbers might not give you the required result.
Have a look at this example
DECLARE #Dec DECIMAL(12,8)
SET #Dec = -123.45
SELECT FLOOR(#DEc)
select round(#Dec, 0, 1)
try this;
DECLARE #result DECIMAL(8,2) = 123.45
SELECT CAST(round(#result,0) AS FLOAT)
SELECT REPLACE(#result % 1 ,'0.','')
OR
DECLARE #result decimal(8,2) = 123.45
select PARSENAME(#result, 2) AS LeftSideValue, PARSENAME(#result, 1) AS RightSideValue