1

I have a situation where a decimal figure isn't truly a decimal, it is a sub-count of sorts. For example, when an prescription for medication is filled it is given an Rx number (lets say 345673). That number will stay with the prescription throughout any refills and the refills append a .1, .2 etc. So, over the life of that Rx number you could end up with 345673, 345673.1, 345673.2... ongoing. The problem is when you hit .10, .20, .30 etc. In decimal form those records are the same as .1, .2, .3.

Is there any way to track these numbers and support the trailing zeros without having use VARCHAR etc? This is the primary key column and I'm not crazy about using varchar on a Pk (is that old fashioned?)

Any and all suggestions/help is appreciated.

Edit to add: I should have explained why we can't use separate columns for this. This data originates elsewhere and is merged into our database from a bulk import operation. The merge is perpetual since much of the data is altered at the origin and combined on the next bulk import. The Rx number has to match exactly to perform the bulk import / merge.

4

2 回答 2

1

我建议使用composite primary key. 添加第二列,可能称为refill,并将其用于增量值。这样,两列都是整数,无需使用 varchar 作为主键。

您可能需要使用 atrigger来维护该值,因为identity字段不适用于分组。

于 2013-10-30T01:56:04.813 回答
1

将小数转换为varchar使用CONVERTCAST。然后您可以使用字符/字符串函数,例如LEFT(),SUBSTRING()REPLACE().

另一种选择是使用数学解析小数:

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]

上述选择中的最后两列是您想要的两列。以上只是我试图“展示我的作品”,这样你就可以看到我在想什么。“-2”是为了去掉“0”。出LEN()函数的结果。该POWER()函数采用 10 并将其提高到十进制结果的幂。

您只需要将所有引用替换@RxValue为“Rx 编号”的列名即可使其正常工作。如果您想尝试一下,您可以将值更改为@RxValue您想要的任何值,并确保结果符合您的预期。 确保更改@RxValue的数据类型以匹配您的数据类型。

如果是这种情况,您当然可以将“Rx 编号”保留为 PK。您只需添加几个派生列:[Rx ID][Refill Count].

如果您有任何问题,请发表评论。

于 2013-10-30T02:32:10.080 回答