MS SQL自定義函式IsNumeric
阿新 • • 發佈:2018-11-07
判斷字串是否為純數字,負數不算。如'00012','54585','1000'
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[svf_IsNumeric] ( @string NVARCHAR(MAX) ) RETURNS BIT --函式返BIT資料型別,是數字返回1,非數字返回0。 AS BEGIN DECLARE @rtv BIT = 1 DECLARE @str NVARCHAR(MAX) = LTRIM(RTRIMSource Code(ISNULL(@string,''))) --去除前後空格,如果為NULL轉為'' DECLARE @start INT = 1; DECLARE @end INT = LEN(@str) --獲取字串長度 WHILE (@start <= @end) --迴圈字串每一個字元 BEGIN DECLARE @Numeric VARCHAR(1) = '' SET @Numeric = SUBSTRING(@str, @start, @start + 1) -- 每迴圈一次,從左邊獲取一位字元IF ASCII(@Numeric) >= 48 AND ASCII(@Numeric) <= 57 --如果是數字 BEGIN SET @start = @start + 1; CONTINUE --繼續迴圈 END ELSE BEGIN SET @rtv = 0 BREAK --跳出迴圈 END END RETURN @rtvEND
建立一個例子來演示:
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] GOSource Code