2023年7月19日 星期三

MS SQL 計算字串中的全形、半形,各佔幾個字

計算字串中的全形、半形,各佔幾個字。

DECLARE @MSG nvarchar(500),@OrderNo int,@x1 int,@s1 int;

--假設@MSG為要計算的字串內容
Set @MSG=N'零壹貳參肆伍陸柒捌玖拾零壹貳參肆伍陸柒捌玖拾零壹貳參肆伍陸柒捌玖拾零壹貳參肆伍陸柒捌玖拾零壹貳參肆伍陸柒捌玖拾零壹貳參肆伍陸柒捌玖ab,cdA。';

Set @x1=LEN(@MSG);
Set @s1=1;

DECLARE @fullWidthCount INT,@halfWidthCount INT;
Set @fullWidthCount=0;
Set @halfWidthCount=0;

WHILE (@s1<=@x1)
BEGIN
IF (UNICODE(SUBSTRING(@MSG, @s1, 1)) > 255)
Begin
Set @fullWidthCount=@fullWidthCount+1;
End
ELSE
Begin
Set @halfWidthCount=@halfWidthCount+1;
End
--加1
Set @s1=@s1+1
END

print DATALENGTH(@MSG);
print LEN(@MSG);
print 'fullWidthCount='+Convert(varchar,@fullWidthCount)+';halfWidthCount='+Convert(varchar,@halfWidthCount);