问题
There is a nvarchar(100) column named value
, when users insert into this column I need to check this code below in a trigger:
if exists
(
select *
from inserted i
where isnumeric(value)=0
)
begin
rollback transaction
raiserror('when productType is numeric, You have to insert numeric character',18,1)
return
end
but in application interface numbers inserted in persian, so always isnumeric(value)=0
.
For example I need to if user insert ۴۵
in interface in my trigger value shown as 45
.
So far I use CAST
,CONVERT
and collate Persian_100_CI_AI
but I couldn't get any result.
Thanks.
回答1:
Which version of SQL Server
? v2017+ offers a new function TRANSLATE.
Might be, there is a more elegant way, but a pragmatic one is this:
DECLARE @PersianNumber NVARCHAR(100)=N'۴۵';
SELECT CAST(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(@PersianNumber,N'۰',N'0'),N'۱',N'1'),N'۲',N'2'),N'۳',N'3'),N'۴',N'4')
,N'۵',N'5'),N'۶',N'6'),N'۷',N'7'),N'۸',N'8'),N'۹',N'9') AS INT);
回答2:
Take a look at this topic, it's the opposite of what you asked but it might help you if you could reverse it :
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/a44ce5c1-d487-4043-be73-b64fa98ed7a5/converting-english-numbers-to-arabic-numbers-and-vice-versa
If you are using the latest version of sql server, try this link :
https://docs.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql
the obvious thing is that SQL does not have a solution out-of-the-box and you have to implement some kind of function yourself and use the returned value in the WHERE
statement.
I have used Shungo's answer to implement the function you need (also works for English numbers or a mix of both):
CREATE FUNCTION IS_NORMALIZED_NUMBER (@PersianNumber NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
BEGIN
SET @PersianNumber = CAST(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(@PersianNumber,N'۰',N'0'),N'۱',N'1'),N'۲',N'2'),N'۳',N'3'),N'۴',N'4')
,N'۵',N'5'),N'۶',N'6'),N'۷',N'7'),N'۸',N'8'),N'۹',N'9') AS NVARCHAR(MAX));
RETURN ISNUMERIC(@PersianNumber)
END
Here is a more optimized version (which will only work for Persian numbers) :
CREATE FUNCTION IS_NUMBER (@PersianNumber NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
BEGIN
RETURN IIF(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(@PersianNumber,N'۰',N''),N'۱',N''),N'۲',N''),N'۳',N''),N'۴',N'')
,N'۵',N''),N'۶',N''),N'۷',N''),N'۸',N''),N'۹',N'') = N'',1 ,0 );
END
来源:https://stackoverflow.com/questions/49511465/how-to-convert-persian-number-to-int