我试图重写以下代码以使用变量而不是幻数:
SELECT tokenId,
IIF(LEN(ref) < 4, ref, REPLICATE(CONVERT(NVARCHAR(20),'*'), LEN(ref)-4) + SUBSTRING(ref, (LEN(ref)-3), LEN(ref))) as refMasked
FROM tokenBase
WHERE (refMasked is null or refMasked = '') AND ref is not null AND ref <> ''
我尝试这样做:
DECLARE @NumberOfCharsAtEndOfStringToNotMask INTEGER
SET @NumberOfCharsAtEndOfStringToNotMask = 4 --Why do I need to set this to 2 for it to work?
SELECT tokenId,
IIF(LEN(ref) < @NumberOfCharsAtEndOfStringToNotMask, ref, REPLICATE(CONVERT(NVARCHAR(20),'*'), LEN(ref)-@NumberOfCharsAtEndOfStringToNotMask) + SUBSTRING(ref, (LEN(ref)-@NumberOfCharsAtEndOfStringToNotMask-1), LEN(ref))) as refMasked
FROM tokenBase
WHERE (refMasked is null or refMasked = '') AND ref is not null AND ref <> ''
但是如果我使用@NumberOfCharsAtEndOfStringToNotMask = 4
它不起作用,我需要使用2代替。为什么是这样?
如果我使用4,那么字符串的最后6个字符将被取消屏蔽,但是我需要将最后4个字符取消屏蔽。使用值2修复此问题,但我不明白为什么。
修改 Amit建议我使用以下代码:
IIF(LEN(ref) < @NumberOfCharsAtEndOfStringToNotMask, ref,REPLICATE(CONVERT(NVARCHAR(20),'*'), LEN(ref)-@NumberOfCharsAtEndOfStringToNotMask) + SUBSTRING(ref, (LEN(ref)-@NumberOfCharsAtEndOfStringToNotMask+1),@NumberOfCharsAtEndOfStringToNotMask)) as refMasked
为什么这样做?为什么我不能用存储4的值的变量替换4的使用?
答案 0 :(得分:1)
将iif
块替换为此块,看看你如何进行
IIF(LEN(ref) < @NumberOfCharsAtEndOfStringToNotMask, ref,REPLICATE(CONVERT(NVARCHAR(20),'*'), LEN(ref)-@NumberOfCharsAtEndOfStringToNotMask) + SUBSTRING(ref, (LEN(ref)-@NumberOfCharsAtEndOfStringToNotMask+1),@NumberOfCharsAtEndOfStringToNotMask)) as refMasked
答案 1 :(得分:1)
试试这个戴夫:
DECLARE @C INTEGER = 4;
SELECT bpayreference
, LEN(bpayreference) As LengthOfString
, LEN(bpayreference) - @C AS MinusC
, SUBSTRING(bpayreference , (LEN(bpayreference) - @C) + 1 , (LEN(bpayreference) ) - (LEN(bpayreference) - @C))
, CASE
WHEN (LEN(bpayreference) < @C) THEN REPLICATE('*' , LEN(bpayreference) - @C)
ELSE
REPLICATE('*' , LEN(bpayreference) - @C )
+ SUBSTRING(bpayreference , (LEN(bpayreference) - @C) + 1 , (LEN(bpayreference) ) - (LEN(bpayreference) - @C))
END
FROM tokenbase