T-SQL : how to disable overflow checks on integer operations? - tsql

In C# we have unchecked to disable overflow checks on integer operations
int int1;
unchecked
{
int1 = 2147483647 + 10;
}
The integer arithmetic result will wrap to -2,147,483,639
But in T-SQL I can't find a way to disable bounds checks
DECLARE #INT1 INT
SET #INT1 = 2147483647 + 10
Results in error:
Msg 8115, Level 16, State 2, Line 2
Arithmetic overflow error converting expression to data type int.

Not that I think this is necessarily a great idea, but you could wrap it in a try/catch.
declare #int int;
begin try
set #int = 2147483647 + 10
end try
begin catch
if ERROR_NUMBER() = 8115
set #int = 2147483647
else
select
ERROR_NUMBER() AS ErrorNumber
,ERROR_MESSAGE() AS ErrorMessage;
end catch
select #int
Result:
2147483647

It's not possible to perform that operation (2147483647 + 10) since the INT data type ranges from -2,147,483,648 to 2,147,483,647, according to the Microsoft specification.
Instead, you can use the BIGINT data type, like this:
DECLARE #number BIGINT;
SET #number = CAST(2147483647 AS BIGINT) + 10;
SELECT #number;
-- Output: 2147483657, as expected

You can cast the int values to bigint, perform the addition and then handle the overflow while converting back to an int using a case expression thusly:
declare #MaxInt as BigInt = Power( Cast( 2 as BigInt ), 31 ) - 1;
declare #Foo as Int = 2147483647;
declare #Bar as Int = 10;
declare #BigSum as BigInt;
set #BigSum = #Foo + Cast( 10 as BigInt );
select #MaxInt as MaxInt, #Foo as Foo, #Bar as Bar, #BigSum as BigSum,
case when #BigSum <= #MaxInt then Cast( #BigSum as Int ) else
Cast( #BigSum - Power( Cast( 2 as BigInt ), 32 ) as Int ) end as Unsigned;
Update: A tidier example showing how to take a BigInt result (from prior calculations) and convert it to an Int without overflow:
declare #Samples as Table ( Value BigInt );
insert into #Samples ( Value ) values
-- NB: At least one literal value needs to be cast as a BigInt to get BigInt values. No, really.
( Cast( 0x0 as BigInt ) ), ( 0x1 ), ( 0x7FFFFFFF ), ( 0x80000000 ), ( 0x80000001 ), ( 0xFFFFFFFF ),
( -1 ), ( 0x4200000001 ), ( 0x7080000000 ); -- Some BigInt values beyond 32 bits.
select Value, Cast( Value as Binary(8) ) as ValueHex,
Value & 0xFFFFFFFF as LSB32, Cast( Value & 0xFFFFFFFF as Binary(8) ) as LSB32Hex,
Cast( case when Value & 0x80000000 = 0 then Value & 0xFFFFFFFF else
( Value & 0x7FFFFFFF ) - Cast( 0x80000000 as BigInt ) end as Int ) as IntResult
from #Samples;
The conversion could be bundled off into a UDF, though the performance may suffer.

I've not found a way to allow integer operations to overflow.
As others have said you just have to do the operation on the value converted to BIGINT instead.
You can (if you want) then convert the result of the operation back to an INT - as though it was an unchecked int operation - and the key to that is to just take the result MOD 2^32 (in SQL Server "%" is the MOD operation)
Heres a little function I've written to convert a BIGINT to an INT unchecked (ie allowing overflow) that will also handle negative values
CREATE FUNCTION dbo.BigIntToUncheckedInt(#input BIGINT)
RETURNS INT AS
BEGIN
-- select the result MOD 2^32 (the max of an unsigned int)
-- this will give a result < 4294967296 (if +ve input), or > -4294967296 (if -ve input)
SELECT #input = #input % 4294967296
-- if we have the result > INT MaxVal - do one final subtraction of 2^32 (resulting in a valid negative INT)
IF #input > 2147483647 BEGIN SELECT #input = #input - 4294967296 END
-- if we have the result < INT MinVal - do one final addition of 2^32 (resulting in a valid positive INT)
IF #input < -2147483648 BEGIN SELECT #input = #input + 4294967296 END
RETURN CAST(#input AS INT)
END
GO
You can then do whatever operation you want and convert it back to an INT (unchecked) with this function, eg:
DECLARE #INT1 BIGINT
SET #INT1 = CAST(2147483647 AS BIGINT) + 10
SELECT dbo.BigIntToUncheckedInt(#INT1)
-- result = -2147483639

Related

Sum all ascii values for every character of varchar in PostgreSQL

I have a table I want to partition based on HASH. This table has a column with varchar, which is the key I want to use to partition.
Ofc. I can't partition based on HASH with varchar, therefore I will SUM all the ASCII values of each character in the varchar.
I hope to get some help to stitch together a function, which takes a varchar parameter and returns the SUM as an INTEGER.
I have tried several variations - some of them commented out -, this is how it looks so far:
CREATE OR REPLACE FUNCTION sum_string_ascii_values(theString varchar)
RETURNS INTEGER
LANGUAGE plpgsql
AS
$$
DECLARE
theSum INTEGER;
BEGIN
-- Sum on all ascii values coming from the every single char from the input varchar.
SELECT SUM( val )
FROM LATERAL ( SELECT ASCII( UNNEST( STRING_TO_ARRAY( LOWER(theString), null) ) ) ) AS val
INTO theSum;
--SELECT SUM(val) FROM ASCII( UNNEST( STRING_TO_ARRAY( LOWER(theString), null) ) ) AS val INTO theSUM;
--RETURN SUM( ASCII( UNNEST( STRING_TO_ARRAY( LOWER(theString), null) ) ) );
RETURN theSUM;
END;
$$;
I hope someone will be able to write and explain a solution to this problem.
Instead of using SELECT to sum the characters, you can loop through the string instead
CREATE OR REPLACE FUNCTION sum_string_ascii_values(input text) RETURNS int LANGUAGE plpgsql AS $$
DECLARE
hash int = 0;
pos int = 0;
BEGIN
WHILE pos <= length(input) LOOP
hash = hash + ascii(upper(substr(input, pos, 1)));
pos = pos + 1;
END LOOP;
RETURN hash;
END;
$$;
Here is a link to a dbfiddle to demonstrate https://dbfiddle.uk/yfhpHyT1

Coverting/ Casting operators to integer

I want to convert/ cast these operators ( '/' and '*') if this is possible. Maybe you know how that works or you know what the internal coding of division and multiplication is?! Maybe then I can continue with that?
What I want to do is, based on the last number of the current system time, I want to decide if that number is odd or even, and then do a multiplication or division in the next calculations.
CREATE FUNCTION CalculateFactor()
RETURNS NVARCHAR(50)
AS
BEGIN
DECLARE #time DATETIME2(7)
DECLARE #length INT
DECLARE #value NVARCHAR(20)
DECLARE #operator NVARCHAR(20)
SET #time = SYSDATETIME()
SELECT #length = LEN(#time)
SELECT #value = RIGHT(#time, 1);
IF (#value % 2 = 0)
SET #operator = '*'
ELSE SET #operator = '/'
DECLARE #SQL NVARCHAR(20)
SET #SQL = '10' + #operator + '2' --I get only 10 / 2 and 10 * 2 because that are strings and that is why I cannot get a result of the operation, but I want 5 and 20
RETURN #SQL
END
GO

T-SQL Syntax - word parser

I have a word list in a variable. The words are comma delimited. I am trying to save them to individual record in a database. I found another question which does this and works, but it saves every word. I tried to modify it so that I only save unique words, and count duplicate as I go. I think the logic below is correct, but my syntax is not working.
if #FoundWord = 0 SET #WordsUsed = #WordsUsed + '' + #Word + ''
** is not concatenating the next word onto the end of the #WordsUsed variable
if #FoundWord = 0 INSERT INTO mydata.dbo.words (ProjectNumber, WordCount, Word) VALUES( '5', '1', #Word )
** doesn't seem to be doing anything at all ... I'm getting no records written to the words table
The entire code follows:
declare #SplitOn nvarchar(5) = ','
BEGIN
DECLARE #split_on_len INT = LEN(#SplitOn)
DECLARE #start_at INT = 1
DECLARE #end_at INT
DECLARE #data_len INT
DECLARE #WordsUsed varchar(max)
DECLARE #FoundWord int
DECLARE #Word varchar(100)
Set #WordsUsed = '**'
WHILE 1=1
BEGIN
SET #end_at = CHARINDEX(#SplitOn,#txt1,#start_at)
SET #data_len = CASE #end_at WHEN 0 THEN LEN(#txt1) ELSE #end_at-#start_at END
set #Word = SUBSTRING(#txt1,#start_at,#data_len)
SET #FoundWord = CHARINDEX('*' & #Word & '*', #WordsUsed)
if #FoundWord = 0 SET #WordsUsed = #WordsUsed & '*' & #Word & '*'
if #FoundWord = 0 INSERT INTO mydata.dbo.words (ProjectNumber, WordCount, Word) VALUES( '5', '1', #Word )
if #FoundWord > 0 Update mydata.dbo.words set WordCount = WordCount + 1 where projectnumber = 5 and word = #word
IF #end_at = 0 BREAK
SET #start_at = #end_at + #split_on_len
END
RETURN
END;
Here's a function you can try. It splits an unlimited-sized string based on the delimiter of your choice. The output of the function is a table - so you can then select distinct from that to store your word list. You'd call it something like:
insert YourWordlistTable ( Word ) --> just making up table/column names here
select distinct Data
from dbo.StringSplit( #yourVar, ',' )
Here's the definition of the function:
create function dbo.StringSplit
(
#string nvarchar( max ),
#delimiter nvarchar( 255 )
)
returns #t table ( Id int, Data nvarchar( 4000 ) )
as begin
with Split( startPosition, endPosition )
as
(
select
cast( 0 as bigint ) as startPosition,
charindex( #delimiter, #string ) as endPosition
union all
select
endPosition + 1, charindex( #delimiter, #string, endPosition + 1 )
from
Split
where
endPosition > 0
)
insert #t
select
row_number() over ( order by ( select 1 ) ) as Id,
substring( #string, startPosition, coalesce( nullif( endPosition, 0 ), len( #string ) + 1 ) - startPosition ) collate Latin1_General_CS_AS as Data
from
Split
option( maxrecursion 0 );
return;
end
I originally posted, then deleted, then reposted this when I realized I'd given an inline function I use that never got called on strings longer than 100 words. I've since modified it to support indefinite recursion - although it can't be an inline function this way.
Inline functions are generally faster because SQL can incorporate the inline function's statement into the query plan of the statements that call the function. However, that does not appear to be an option available in an inline function.
why can't you use
select count(distinct value) from dbo.split(',',#txt1) where #txt1 is he string will give you distinct count of words
If you are looking for word wise count
select value,count(1) from dbo.split(',',#txt1) group by value
shoud do this

Convert IP address in PostgreSQL to integer?

Is there a query that would be able to accomplish this?
For example given an entry '216.55.82.34' ..I would want to split the string by the '.'s, and apply the equation:
IP Number = 16777216*w + 65536*x + 256*y + z
where IP Address = w.x.y.z
Would this be possible from just a Query?
You can simply convert inet data-type to bigint: (inet_column - '0.0.0.0'::inet)
For example:
SELECT ('127.0.0.1'::inet - '0.0.0.0'::inet) as ip_integer
will output 2130706433, which is the integer representation of IP address 127.0.0.1
You can use split_part(). For example:
CREATE FUNCTION ip2int(text) RETURNS bigint AS $$
SELECT split_part($1,'.',1)::bigint*16777216 + split_part($1,'.',2)::bigint*65536 +
split_part($1,'.',3)::bigint*256 + split_part($1,'.',4)::bigint;
$$ LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT;
SELECT ip2int('200.233.1.2');
>> 3370713346
Or, if don't want to define a function, simply :
SELECT split_part(ip,'.',1)::bigint*16777216 + split_part(ip,'.',2)::bigint*65536 +
split_part(ip,'.',3)::bigint*256 + split_part(ip,'.',4)::bigint;
The drawback of the later is that, if the value is given by some computation instead of being just a table field, it can be inefficient to compute, or ugly to write.
PG 9.4
create or replace function ip2numeric(ip varchar) returns numeric AS
$$
DECLARE
ip_numeric numeric;
BEGIN
EXECUTE format('SELECT inet %L - %L', ip, '0.0.0.0') into ip_numeric;
return ip_numeric;
END;
$$ LANGUAGE plpgsql;
Usage
select ip2numeric('192.168.1.2');
$ 3232235778
create function dbo.fn_ipv4_to_int( p_ip text)
returns int
as $func$
select cast(case when cast( split_part(p_ip, '.', 1 ) as int ) >= 128
then
(
( 256 - cast(split_part(p_ip, '.', 1 ) as int ))
*
-power ( 2, 24 )
)
+ (cast( split_part(p_ip, '.', 2 ) as int ) * 65536 )
+ (cast( split_part(p_ip, '.', 3 ) as int ) * 256 )
+ (cast( split_part(p_ip, '.', 4 ) as int ) )
else (cast(split_part(p_ip, '.', 1 ) as int) * 16777216)
+ (cast(split_part(p_ip, '.', 2 ) as int) * 65536)
+ (cast(split_part(p_ip, '.', 3 ) as int) * 256)
+ (cast(split_part(p_ip, '.', 4 ) as int))
end as int )
$func$ LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT;
in case you need to get a 32 bit int. it'll return negative numbers for ips over 128.0.0.0. I'd use bigint if you can, but i had a case when i had the numbers stored as 32 bit numbers from another database.
Consider changing the column data type to inet, maybe is more efficient.
ALTER TABLE iptable ALTER COLUMN ip_from TYPE inet
USING '0.0.0.0'::inet + ip_from::bigint;
create index on iptable using gist (ip_from inet_ops);
Then to query
SELECT ip_from
FROM iptable
WHERE ip_from = '177.99.194.234'::inet

Add comma every nth character in value

my problem is pretty simple. I get a value from a sql select which looks like this:
ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG
and I need it like this:
AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO,FI,FR,GE,GR,IE,IS,IT,JP,YU,CA,KZ,KG
The length is different in each dataset.
I tried it with format(), stuff() and so on but nothing brought me the result I need.
Thanks in advance
With a little help of a numbers table and for xml path.
-- Sample table
declare #T table
(
Value nvarchar(100)
)
-- Sample data
insert into #T values
('ARAMAU'),
('ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG')
declare #Len int
set #Len = 2;
select stuff(T2.X.value('.', 'nvarchar(max)'), 1, 1, '')
from #T as T1
cross apply (select ','+substring(T1.Value, 1+Number*#Len, #Len)
from Numbers
where Number >= 0 and
Number < len(T1.Value) / #Len
order by Number
for xml path(''), type) as T2(X)
Try on SE-Data
Time to update your resume.
create function DontDoThis (
#string varchar(max),
#count int
)
returns varchar(max)
as
begin
declare #result varchar(max) = ''
declare #token varchar(max) = ''
while DATALENGTH(#string) > 0
begin
select #token = left(#string, #count)
select #string = REPLACE(#string, #token, '')
select #result += #token + case when DATALENGTH(#string) = 0 then '' else ',' end
end
return #result
end
Call:
declare #test varchar(max) = 'ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG'
select dbo.DontDoThis(#test, 2)
gbn's comment is exactly right, if not very diplomatic :) TSQL is a poor language for string manipulation, but if you write a CLR function to do this then you will have the best of both worlds: .NET string functions called from pure TSQL.
I believe this is what QQping is looking for.
-- select .dbo.DelineateEachNth('ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG',2,',')
create function DelineateEachNth
(
#str varchar(max), -- Incoming String to parse
#length int, -- Length of desired segment
#delimiter varchar(100) -- Segment delimiter (comma, tab, line-feed, etc)
)
returns varchar(max)
AS
begin
declare #resultString varchar(max) = ''
-- only set delimiter(s) when lenght of string is longer than desired segment
if LEN(#str) > #length
begin
-- continue as long as there is a remaining string to parse
while len(#str) > 0
begin
-- as long as know we still need to create a segment...
if LEN(#str) > #length
begin
-- build result string from leftmost segment length
set #resultString = #resultString + left(#str, #length) + #delimiter
-- continually shorten result string by current segment
set #str = right(#str, len(#str) - #length)
end
-- as soon as the remaining string is segment length or less,
-- just use the remainder and empty the string to close the loop
else
begin
set #resultString = #resultString + #str
set #str = ''
end
end
end
-- if string is less than segment length, just pass it through
else
begin
set #resultString = #str
end
return #resultString
end
With a little help from Regex
select Wow=
(select case when MatchIndex %2 = 0 and MatchIndex!=0 then ',' + match else match end
from dbo.RegExMatches('[^\n]','ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG',1)
for xml path(''))