Convert the decimal to varchar
using either CONVERT
or CAST
. Then you can use character/string functions such as LEFT()
, SUBSTRING()
, and REPLACE()
.
The other option is to parse out the decimal using math:
DECLARE @RxValue decimal(18,4) = 100.234
SELECT @RxValue [Rx Number]
,@RxValue - CONVERT(int,@RxValue) [Refill Count Decimal]
,LEN(CONVERT(float,(@RxValue - CONVERT(int,@RxValue))))-2 [After Decimal Length]
,POWER(10, LEN(@RxValue - CONVERT(int,@RxValue))-2) [Calc multiplier for Refill Count]
,CONVERT(int,@RxValue) [Rx ID]
,CONVERT(int,(@RxValue - CONVERT(int,@RxValue)) * POWER(10, LEN(CONVERT(float,(@RxValue - CONVERT(int,@RxValue))))-2)) [Refill Count]
The last two columns in the above select are your two desired columns. All that is above is my attempt to "show my work" so you can see what I was thinking. The "-2" is to to remove the "0." out of the LEN()
function's result. The POWER()
function takes the 10 and raises it to the power of the decimal result.
You should only need to replace all references to @RxValue
with the column name of your "Rx number" to make it work. If you want to play around with it, you can change the values in @RxValue
to whatever you want and make sure the result is what you expect. Be sure you change @RxValue
's data type to match yours.
You can, of course keep your "Rx number" as the PK if that is the situation it is in. You'll just be adding a couple of derived columns: [Rx ID]
and [Refill Count]
.
Please leave a comment if you have a question.