我发现拥有一个函数非常有用,该函数在给定文本输入的情况下将返回一个INT
,如果无法解析该值,则返回 NULL 。然后你可以简单地查询
WHERE dbo.ParseInteger(result) >= 3
就我而言,我只对整数感兴趣,但我相信你可以扩展它以适应浮点数。这可能比您需要的更复杂;例如,如果你不关心指数,你可以扔掉 70%。我对 MySQL 太生疏了,无法提供翻译。最后,请注意,我假设的是英文风格的数字,您可能有不同的组和小数分隔符。
CREATE FUNCTION dbo.ParseInteger(@Input VARCHAR(100)) RETURNS BIGINT WITH SCHEMABINDING
AS BEGIN
SET @Input = dbo.Trim(@Input) -- If you're not worried about linebreaks or other odd chars, LTRIM(RTRIM(@Input)) will be fine
IF ISNUMERIC(@Input) = 0 RETURN NULL
IF @Input IN ('.', '+', '-', ',') RETURN NULL
SET @Input = REPLACE(@Input, ',', '') -- Strip commas
DECLARE @DecimalPos INT = CHARINDEX('.', @Input)
DECLARE @ExpPos INT = CHARINDEX('E', @Input)
DECLARE @IntValue BIGINT
IF @DecimalPos = 0 AND @ExpPos = 0
BEGIN
-- There's no decimal and no exponent, so we can easily cast this bog-standard integer
SET @IntValue = CAST(@Input AS BIGINT)
END
ELSE IF @DecimalPos > 0 AND @ExpPos = 0
BEGIN
-- There's a decimal point but no exponent; we can cast the integer part, and then nudge it if necessary to round off the tenths place
SET @IntValue = CAST(SUBSTRING(@Input, 1, @DecimalPos - 1) AS BIGINT)
IF SUBSTRING(@Input, @DecimalPos + 1, 1) BETWEEN '5' AND '9'
IF @IntValue < 0
SET @IntValue -= 1
ELSE
SET @IntValue += 1
END
ELSE
BEGIN
-- There's an exponent, and probably a decimal; this will be relatively complicated
IF @DecimalPos = 0
BEGIN
-- There's no decimal; insert one, just so we have consistency downstream
SET @Input = LEFT(@Input, @ExpPos - 1) + '.0E' + RIGHT(@Input, LEN(@Input) - @ExpPos)
SET @DecimalPos = @ExpPos
SET @ExpPos += 2
END
DECLARE @Magnitude INT = CASE WHEN LEFT(@Input, 1) = '-' THEN @DecimalPos - 2 ELSE @DecimalPos - 1 END -- For normalized scientific notation, this will always be one, but we can't expect that
DECLARE @Exponent INT = CAST(RIGHT(@Input, LEN(@Input) - @ExpPos) AS INT)
IF @Exponent > 18 RETURN NULL -- BIGINT can handle values up to 2^63, or 9.2E18
SET @Input = REPLACE(SUBSTRING(@Input, 1, @ExpPos - 1), '.', '')
DECLARE @MagAdjustment INT = @Magnitude + @Exponent - CASE WHEN LEFT(@Input, 1) = '-' THEN LEN(@Input) - 1 ELSE LEN(@Input) END
IF @MagAdjustment > 0
BEGIN
SET @Input += REPLICATE('0', @MagAdjustment)
END
ELSE IF @MagAdjustment < 0
BEGIN
WHILE -@MagAdjustment > @Magnitude AND LEN(@Input) > 1
BEGIN
SET @MagAdjustment += 1
SET @Input = SUBSTRING(@Input, 1, LEN(@Input) - 1)
END
IF -@MagAdjustment > @Magnitude SET @Input = '0'
ELSE IF -@MagAdjustment = @Magnitude SET @Input = CASE WHEN LEFT(@Input, 1) BETWEEN '5' AND '9' THEN '1' WHEN LEFT(@Input, 2) BETWEEN '-5' AND '-9' THEN '-1' ELSE '0' END
ELSE SET @Input = SUBSTRING(@Input, 1, CASE WHEN LEFT(@Input, 1) = '-' THEN 1 ELSE 0 END + LEN(@Input) + @MagAdjustment)
END
SET @IntValue = CAST(@Input AS BIGINT)
END
RETURN @IntValue
END