本人是長沙軟件開發(fā)公司簡界程序員小伍,最近在做一個(gè)小功能,判斷字符串是否為純數(shù)字,負(fù)數(shù)不算。如'00012','54585','1000'
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[svf_IsNumeric]
(
@string NVARCHAR(MAX)
) RETURNS BIT --函數(shù)返BIT數(shù)據(jù)類型,是數(shù)字返回1,非數(shù)字返回0。
AS
BEGIN
DECLARE @rtv BIT = 1
DECLARE @str NVARCHAR(MAX) = LTRIM(RTRIM(ISNULL(@string,''))) --去除前后空格,如果為NULL轉(zhuǎn)為''
DECLARE @start INT = 1;
DECLARE @end INT = LEN(@str) --獲取字符串長度
WHILE (@start <= @end) --循環(huán)字符串每一個(gè)字符
BEGIN
DECLARE @Numeric VARCHAR(1) = ''
SET @Numeric = SUBSTRING(@str, @start, @start + 1) -- 每循環(huán)一次,從左邊獲取一位字符
IF ASCII(@Numeric) >= 48 AND ASCII(@Numeric) <= 57 --如果是數(shù)字
BEGIN
SET @start = @start + 1;
CONTINUE --繼續(xù)循環(huán)
END
ELSE
BEGIN
SET @rtv = 0
BREAK --跳出循環(huán)
END
END
RETURN @rtv
END
Source Code
創(chuàng)建一個(gè)例子來演示:
CREATE TABLE [dbo].[uTable] ([col1] NVARCHAR(20),[col2] NVARCHAR(20),[col3] NVARCHAR(20),[col4] NVARCHAR(20),[col5] NVARCHAR(20),[col6] NVARCHAR(20),[col7] NVARCHAR(20))
GO
INSERT INTO [dbo].[uTable] ([col1],[col2],[col3],[col4],[col5],[col6],[col7])
VALUES ('0.455','000435','SF46DG','4000','$%9KJ','-0034','-8554')
GO
SELECT [dbo].[svf_IsNumeric] ([col1]) AS [col1],
[dbo].[svf_IsNumeric] ([col2]) AS [col2],
[dbo].[svf_IsNumeric] ([col3]) AS [col3],
[dbo].[svf_IsNumeric] ([col4]) AS [col4],
[dbo].[svf_IsNumeric] ([col5]) AS [col5],
[dbo].[svf_IsNumeric] ([col6]) AS [col6],
[dbo].[svf_IsNumeric] ([col7]) AS [col7]
FROM [dbo].[uTable]
GO
Source Code
——本文并非原創(chuàng),如有侵權(quán)請聯(lián)系管理員刪除。