SQL Base32 Conversion - sql

I am writing a SQL Function that will take in a decimal and return the base32 representation of that decimal.
My problem is with the decimal to ascii conversion.
I am allowed to run the following query and return an ascii character
"SELECT CHAR( 65 )" which returns "A"
However in my function when I am trying to build my output string of letters, I am having trouble casting a bigint into a char, then concatenate that char to the end of a another char(which would be my output).
Sample line of code: "SET #OutputChar = #OutputChar + CAST( ( #Output + 55 ) AS CHAR(255) )"
What is the proper way to cast a bigint to char and then concatenate that char to another?
Thanks

How are you declaring #OutputChar?
If you have:
DECLARE #OutputChar CHAR(255)
then every time you concantenate, it will truncate it to 255. CHAR includes the whitespace at the end, maybe you mean to use varchar instead of CHAR?

Try this:
SET #OutputChar = #OutputChar + CONVERT(varchar(255),#Output + 55)

Related

Error converting varchar value to data type int

I am trying to concatenate two integer values with hyphen in between. So when I try to do the same, SQL gives me the error.
Conversion failed when converting the varchar value '30-45' to data type int.
NOTE:
Also, the second value for concatenation can be null so in that case, a hyphen should not be concatenated.
example
from1 = 30
to1 = 45
case
to1 is null
then from1
else CONCAT(from1, '-' + nullif(to1,'')) end
AS age
//This works but shows 3045 instead of 30-45.
concat(from, '-', to) AS age
//This doesn't work out as it gives the error 'Conversion failed when converting the varchar value '30-45' to data type int.'
Thanks for the help in advance and looking forward to it.
DECLARE #FROM INT=30;
DECLARE #TO INT=45;
SELECT CAST(#FROM AS VARCHAR(2))+'-'+CAST(ISNULL(#TO,'') AS VARCHAR(2));
SQL is trying to convert your phrase to int probably because it's part of CASE statement. It uses the first route to determine the output type.
In your case- you put NULL as the first route option in your CASE, so it is determined as int. try putting instead of it this: CAST(NULL AS VARCHAR(10))
It seems that for some reason you think that strings that contain mathematical expressions are resolved as said expression, not an as literal string. Thus if you have the varchar value '30-45' you think it'll return the int value -15; this isn't true. This in fact isn't true in any language, let alone T-SQL.
For what you have, in your ELSE the '-' isn't a minus... It's a string... - is a minus. If you want to substract a number from another then it's a basic maths expression: a - b. You're effectively doing CONVERT(varchar,a) + '-' + CONVERT(varchar,b)... Just have your ELSE as the following:
from1 - NULLIF(to1,0)
This will return NULL if from1 has the value NULL, or to1 has the value NULL or 0.
Please check below code. It's working
example
#from1 = 30
#to1 = 45
IF #to1 is null
SELECT #from1
ELSE
SELECT CONCAT(#from1, '-' , nullif(#to1,'')) as age

How can i extract unicode concat string in SQL Server

I would like to extract last value after the "dot".
When I copy the cell value --> it shows like 00.250.980.80.19
Is this Unicode stuff?
How can I decode the string and extract the last one?
Thanks
You can use the ASCII function to find the code of your dot. For example:
SELECT ASCII(N'·'); -- 183
Then, you can use CHAR function to transform an int ASCII code to a character value and SUBSTRING:
DECLARE #string NVARCHAR(32) = N'·05·201·41·321·32·501';
SELECT REVERSE(SUBSTRING(REVERSE(#string), 0, CHARINDEX(CHAR(183), REVERSE(#string)))); -- 501
of course if you can simply use the char itself:
DECLARE #string NVARCHAR(32) = N'·05·201·41·321·32·501';
SELECT REVERSE(SUBSTRING(REVERSE(#string), 0, CHARINDEX('·', REVERSE(#string)))); -- 501

How to handle a input into function which can be float or nvarchar (Function parameter is varchar)

I created a function [fnRemoveNonNumericCharacters] which takes phone numbers as input remove any characters other than numeric and returns only numeric part.
Example : if I pass (800)-123-1234 in to the function it removes the non numeric character and returns me 8001231234.
My inputs will be phone number which usually are float datatype. So I used
select [dbo].[fnRemoveNonNumericCharacters](Ltrim(str(Phone, 50, 0)))
to pass through and it used to work fine. But now I am getting nvarchar numbers like (800)-123-1234 as a source.
When I am using the above function it's erroring out:
'Error converting data type nvarchar to float'
Here is the function which I am using
Create Function [dbo].[fnRemoveNonNumericCharacters](#strText VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^0-9]%', #strText) > 0
BEGIN
SET #strText = STUFF(#strText, PATINDEX('%[^0-9]%', #strText), 1, '')
END
IF (#strText Like '1%')
BEGIN
SET #StrText = Stuff(#StrText,1,1,'')
END
RETURN #strText
END
How can I handle both nvarchar and float numbers while passing in to the above function?
The STR function in sql server ex expecting a float datatype as the first argument and in this case your input is not float datatype , it is a nvarchar type. To solve this problem, i will suggest use the substring function with Cast function. Please find the sample sql below.
select ltrim(Substring(cast(phone_number as nvarchar(100)),0,50)) from test_phone
Here first you change the phone_number data type from float to navrachar and then using sub string you are collecting first 50 character and Ltrim for trimming purpose.
You can try this and hopefully your problem will be fixed.
Note: there are different ways to solve the same problem, the above problem may not be optimized one.
Regards - Sanjeeb

How to convert Varchar to Int in sql server 2008?

How to convert Varchar to Int in sql server 2008.
i have following code when i tried to run it wont allowed me to convert Varchar to Int.
Select Cast([Column1] as INT)
Column1 is of Varchar(21) NOT NULL type and i wanted to convert it into Int.
actually i am trying to insert Column1 into another table having Field as INT.
can someone please help me to convert this ?
Spaces will not be a problem for cast, however characters like TAB, CR or LF will appear as spaces, will not be trimmed by LTRIM or RTRIM, and will be a problem.
For example try the following:
declare #v1 varchar(21) = '66',
#v2 varchar(21) = ' 66 ',
#v3 varchar(21) = '66' + char(13) + char(10),
#v4 varchar(21) = char(9) + '66'
select cast(#v1 as int) -- ok
select cast(#v2 as int) -- ok
select cast(#v3 as int) -- error
select cast(#v4 as int) -- error
Check your input for these characters and if you find them, use REPLACE to clean up your data.
Per your comment, you can use REPLACE as part of your cast:
select cast(replace(replace(#v3, char(13), ''), char(10), '') as int)
If this is something that will be happening often, it would be better to clean up the data and modify the way the table is populated to remove the CR and LF before it is entered.
you can use convert function :
Select convert(int,[Column1])
That is how you would do it, is it throwing an error? Are you sure the value you are trying to convert is convertible? For obvious reasons you cannot convert abc123 to an int.
UPDATE
Based on your comments I would remove any spaces that are in the values you are trying to convert.
That is the correct way to convert it to an INT as long as you don't have any alpha characters or NULL values.
If you have any NULL values, use
ISNULL(column1, 0)
Try the following code. In most case, it is caused by the comma issue.
cast(replace([FIELD NAME],',','') as float)
Try with below command, and it will ask all values to INT
select case when isnumeric(YourColumn + '.0e0') = 1
then cast(YourColumn as int)
else NULL
end /* case */
from YourTable
There are two type of convert method in SQL.
CAST and CONVERT have similar functionality. CONVERT is specific to SQL Server, and allows for a greater breadth of flexibility when converting between date and time values, fractional numbers, and monetary signifiers. CAST is the more ANSI-standard of the two functions.
Using Convert
Select convert(int,[Column1])
Using Cast
Select cast([Column1] as int)

SQL - Why is parameter trimmed

I have a table (t) with a column (c) defined as varchar 20, containing the values 'a', 'b' and 'c'
If I execute the following sql, a value is returned:
select * from table where c = 'a '
Why?
I assume it's casting/trimming the parameter in some way, but why?
How would I really search for 'a '
To compare it to a varchar column, your string literal must also be a varchar type. Varchar does trim extra ending white space. It varies, hence VARchar. The plain the char type does not trim the whitespace, and will actually append extra spaces on the end of a literal if need be. You can check for this (and fix your search with the LEN() function:
declare #a varchar(20) = 'a '
select * from t where c = #a and len(#a) = Len(c)
Trailing space is specified to be handled in a special way in the ANSI SQL Standard:
http://support.microsoft.com/default.aspx/kb/316626
http://support.microsoft.com/kb/154886/EN-US/
This behavior is effectively the same for both char and varchar.
I used simple solution:
declare #a varchar(20) = 'a '
select * from t where c + '$' = #a + '$'