Convert decimal to hex string without 0x in SQL Server - sql-server

I want to convert
string
------
BB
C1
GB
to
hex
---
4242
4331
4742
using
SELECT CONVERT(BINARY(2), 'B1')
Result is '0x4231'
but I want remove the 0x from the result, so I tried varbinary to string:
SELECT CONVERT([VARCHAR](MAX), CONVERT(BINARY(2), 'B1', 2))
result is '?'
Then I tried
SELECT SUBSTRING(CONVERT(BINARY(2), 'B1'), 2, 4)
result is '0x42'
How to convert 'B1' to '4231'?

Convert to hex using the system function master.dbo.fn_varbintohexstr, then remove the first two characters.
SELECT SUBSTRING(master.dbo.fn_varbintohexstr(convert(binary(2), 'B1')),3,999)
Output:
4231

solved it myself
SELECT convert(varchar(4), convert(binary(2), ('B1')), 2)

Related

How to mask some digit using SQL Select

I have a column named Number
Suppose a value is 12345678997
and I want to output as *******8997, that means all leading digits will be masked by * except the last 4 digits
how can I achieve this using SQL Server Select ?
Try this:
declare #i bigint = '12345678997'
select stuff(#i,1,len(#i)-4,'*******')
Output:
*******8997
Using REPLICATE you can generate a string with a given number of the same character.
Then just add the last four digits to that.
select
Number,
concat(replicate('*',len(Number)-4), right(Number,4)) as MaskedNumber
from YourTable

SQL Server - How to get last numeric value in the given string

I am trying to get last numeric part in the given string.
For Example, below are the given strings and the result should be last numeric part only
SB124197 --> 124197
287276ACBX92 --> 92
R009321743-16 --> 16
How to achieve this functionality. Please help.
Try this:
select right(#str, patindex('%[^0-9]%',reverse(#str)) - 1)
Explanation:
Using PATINDEX with '%[^0-9]%' as a search pattern you get the starting position of the first occurrence of a character that is not a number.
Using REVERSE you get the position of the first non numeric character starting from the back of the string.
Edit:
To handle the case of strings not containing non numeric characters you can use:
select case
when patindex(#str, '%[^0-9]%') = 0 then #str
else right(#str, patindex('%[^0-9]%',reverse(#str)) - 1)
end
If your data always contains at least one non-numeric character then you can use the first query, otherwise use the second one.
Actual query:
So, if your table is something like this:
mycol
--------------
SB124197
287276ACBX92
R009321743-16
123456
then you can use the following query (works in SQL Server 2012+):
select iif(x.i = 0, mycol, right(mycol, x.i - 1))
from mytable
cross apply (select patindex('%[^0-9]%', reverse(mycol) )) as x(i)
Output:
mynum
------
124197
92
16
123456
Demo here
Here is one way using Patindex
SELECT RIGHT(strg, COALESCE(NULLIF(Patindex('%[^0-9]%', Reverse(strg)), 0) - 1, Len(strg)))
FROM (VALUES ('SB124197'),
('287276ACBX92'),
('R009321743-16')) tc (strg)
After reversing the string, we are finding the position of first non numeric character and extracting the data from that position till the end..
Result :
-----
124197
92
16

Remove the trailing zeros after Decimal points without truncating/ approximating the value in SQL server

Have decimals stored as varchar.
I have a column with value 0.0375000. I need to convert this into 0.0375.
When I did
convert(decimal(8, 7), substring(column, 0, 1) + '.' + substring(column, 2, 8)))
I got the result as 0.0375000.
I want to remove all the trailing zeros and the result I want is 0.0375
How can I do this?
If 2012+ The #'s indicate an optional display
Select format(0.0375000,'0.######') Returns 0.0375
Select format(0.037502,'0.######') Returns 0.037502
Sorry didn't see stored as varchar()
Select format(cast(somecolumn as decimal(18,8)),'0.######')
if you only need 4 decimal places, you want decimal 5,4 (assuming your number to the left of the decimal point fits into 1 digit , if you need 2 digits, choose decimal(6,4) for example )
select convert(decimal(5,4), substring(column,0,1)+'.' +substring(column,2,8) )
decimal data type https://msdn.microsoft.com/en-gb/library/ms187746.aspx
--SQL Code for easy removing trailing zeros.
select CONVERT(DOUBLE PRECISION,'2.256000')
--Result will be 2.256

Convert float into varchar in SQL Server without scientific notation

Convert float into varchar in SQL Server without scientific notation and trimming decimals.
For example:
I have the float value 1000.2324422, and then it would be converted into varchar as same 1000.2324422.
There could be any number of decimal values...the float value comes randomly.
Casting or converting to VARCHAR(MAX) or anything else did not work for me using large integers (in float fields) such as 167382981, which always came out '1.67383e+008'.
What did work was STR().
Neither str() or cast(float as nvarchar(18)) worked for me.
What did end up working was converting to an int and then converting to an nvarchar like so:
convert(nvarchar(18),convert(bigint,float))
The STR function works nice. I had a float coming back after doing some calculations and needed to change to VARCHAR, but I was getting scientific notation randomly as well. I made this transformation after all the calculations:
ltrim(rtrim(str(someField)))
Try CAST(CAST(#value AS bigint) AS varchar)
This works:
CONVERT(VARCHAR(100), CONVERT(DECIMAL(30, 15), fieldname))
Try this:
SELECT REPLACE(RTRIM(REPLACE(REPLACE(RTRIM(REPLACE(CAST(CAST(YOUR_FLOAT_COLUMN_NAME AS DECIMAL(18,9)) AS VARCHAR(20)),'0',' ')),' ','0'),'.',' ')),' ','.') FROM YOUR_TABLE_NAME
Casting as DECIMAL will put decimal point on every value, whether it
had one before or not.
Casting as VARCHAR allows you to use the REPLACE function
First REPLACE zeros with spaces, then RTRIM to get rid of all trailing spaces (formerly zeros), then REPLACE remaining spaces with zeros.
Then do the same for the period to get rid of it for numbers with no decimal values.
This is not relevant to this particular case because of the decimals, but may help people who google the heading.
Integer fields convert fine to varchars, but floats change to scientific notation. A very quick way to change a float quickly if you do not have decimals is therefore to change the field first to an integer and then change it to a varchar.
Below is an example where we can convert float value without any scientific notation.
DECLARE #Floater AS FLOAT = 100000003.141592653
SELECT CAST(ROUND(#Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(#Floater, 0))
,STR(#Floater)
,LEFT(FORMAT(#Floater, ''), CHARINDEX('.', FORMAT(#Floater, '')) - 1)
SET #Floater = #Floater * 10
SELECT CAST(ROUND(#Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(#Floater, 0))
,STR(#Floater)
,LEFT(FORMAT(#Floater, ''), CHARINDEX('.', FORMAT(#Floater, '')) - 1)
SET #Floater = #Floater * 100
SELECT CAST(ROUND(#Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(#Floater, 0))
,STR(#Floater)
,LEFT(FORMAT(#Floater, ''), CHARINDEX('.', FORMAT(#Floater, '')) - 1)
SELECT LEFT(FORMAT(#Floater, ''), CHARINDEX('.', FORMAT(#Floater, '')) - 1)
,FORMAT(#Floater, '')
In the above example, we can see that the format function is useful for us. FORMAT() function returns always nvarchar.
I have another solution since the STR() function would result some blank spaces, so I use the FORMAT() function as folowing example:
SELECT ':' + STR(1000.2324422), ':' + FORMAT(1000.2324422,'##.#######'), ':' + FORMAT(1000.2324422,'##')
The result of above code would be:
: 1000 :1000.2324422 :1000
You can use this code:
STR(<Your Field>, Length, Scale)
Your field = Float field for convert
Length = Total length of your float number with Decimal point
Scale = Number of length after decimal point
For example:
SELECT STR(1234.5678912,8,3)
The result is: 1234.568
Note that the last digit is also round up.
You will have to test your data VERY well. This can get messy. Here is an example of results simply by multiplying the value by 10. Run this to see what happens.
On my SQL Server 2017 box, at the 3rd query I get a bunch of *********. If you CAST as BIGINT it should work every time. But if you don't and don't test enough data you could run into problems later on, so don't get sucked into thinking it will work on all of your data unless you test the maximum expected value.
Declare #Floater AS FLOAT =100000003.141592653
SELECT CAST(ROUND(#Floater,0) AS VARCHAR(30) ),
CONVERT(VARCHAR(100),ROUND(#Floater,0)),
STR(#Floater)
SET #Floater =#Floater *10
SELECT CAST(ROUND(#Floater,0) AS VARCHAR(30) ),
CONVERT(VARCHAR(100),ROUND(#Floater,0)),
STR(#Floater)
SET #Floater =#Floater *100
SELECT CAST(ROUND(#Floater,0) AS VARCHAR(30) ),
CONVERT(VARCHAR(100),ROUND(#Floater,0)),
STR(#Floater)
There are quite a few answers but none of them was complete enough to accommodate the scenario of converting FLOAT into NVARCHAR, so here we are.
This is what we ended up with:
DECLARE #f1 FLOAT = 4000000
DECLARE #f2 FLOAT = 4000000.43
SELECT TRIM('.' FROM TRIM(' 0' FROM STR(#f1, 30, 2))),
TRIM('.' FROM TRIM(' 0' FROM STR(#f2, 30, 2)))
SELECT CAST(#f1 AS NVARCHAR),
CAST(#f2 AS NVARCHAR)
Output:
------------------------------ ------------------------------
4000000 4000000.43
(1 row affected)
------------------------------ ------------------------------
4e+006 4e+006
(1 row affected)
In our scenario the FLOAT was a dollar amount to 2 decimal point was sufficient, but you can easily increase it to your needs.
In addition, we needed to trim ".00" for round numbers.
Try this code
SELECT CONVERT(varchar(max), CAST(1000.2324422 AS decimal(11,2)))
Result:
1000.23
Here decimal(11,2): 11-total digits count (without the decimal point), 2 - for two digits after the decimal point
None of the previous answers for me. In the end I simply used this:
INSERT INTO [Destination_Table_Name]([Field_Name])
SELECT CONCAT('#',CAST([Field_Name] AS decimal(38,0))) [Field_Name]
FROM [dbo].[Source_Table_Name] WHERE ISNUMERIC([CIRCUIT_NUMBER]) = 1
INSERT INTO [Destination_Table_Name]([Field_Name])
SELECT [Field_Name]
FROM [dbo].[Source_Table_Name] WHERE ISNUMERIC([CIRCUIT_NUMBER]) <> 1
select format(convert(float,#your_column),'0.0#########')
Advantage: This solution is independent of the source datatype (float, scientific, varchar, date, etc.)
String is limited to 10 digits, and bigInt gets rid of decimal values.
This works:
Suppose
dbo.AsDesignedBites.XN1E1 = 4016519.564`
For the following string:
'POLYGON(('+STR(dbo.AsDesignedBites.XN1E1, 11, 3)+'...

How to determine the field value which can not convert to (decimal, float,int) in SQL Server

I have a SQL Server database.
One field has values which are like
ID VALUE
1 NEGATIF
2 11.4
3 0.2
4 A RH(+)
5 -----
6 >>>>>
7 5.6<
8 -13.9
I want to CONVERT VALUE field to decimal, of course convert-able fields.
What kind of SQL statement can do this?
How can I understand which value is raising error while converting?
PS: I think this can solve WHERE VALUE LIKE '[a-z]' but how can I add more filter like [-+ ()] ?
Plain ISNUMERIC is rubbish
Empty string, +, - and . are all valid
So is +. etc
1e-3 is valid for float but not decimal (unless you CAST to float then to decimal)
For a particularly cryptic but failsafe solution, append e0 or .0e0 then use ISNUMERIC
SELECT
ISNUMERIC(MyCOl + 'e0') --decimal check,
ISNUMERIC(MyCOl + '.0e0') --integer check
So
SELECT
ID, VALUE,
CAST(
CASE WHEN ISNUMERIC(VALUE + 'e0') = 1 THEN VALUE ELSE NULL END
AS decimal(38, 10)
) AS ConvertedVALUE
FROM
Mytable

Resources