判断数字是否为奇数或偶数

判断数字是否为奇数或偶数,可以参考下面2个自定义函数:

奇数:

判断数字是否为奇数或偶数_第1张图片

 

 
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Insus.NET
-- Blog:        https://insus.cnblogs.com
-- Create date: 2019-06-02
-- Update date: 2019-06-02
-- Description: 是否为奇数
-- =============================================
 CREATE FUNCTION [dbo].[svf_IsOdd]
 (
    @number INT
 )
 RETURNS BIT
 AS
 BEGIN    
    RETURN CASE WHEN @number % 2 <> 0 THEN 1 ELSE 0 END
 END
 GO
Source Code

 

偶数:

判断数字是否为奇数或偶数_第2张图片

 

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Insus.NET
-- Blog:        https://insus.cnblogs.com
-- Create date: 2019-06-02
-- Update date: 2019-06-02
-- Description: 是否为偶数
-- =============================================
 CREATE FUNCTION [dbo].[svf_IsEven]
 (
    @number INT
 )
 RETURNS BIT
 AS
 BEGIN    
    RETURN CASE WHEN @number % 2 = 0 THEN 1 ELSE 0 END
 END
 GO
Source Code

 

举例说明:

判断数字是否为奇数或偶数_第3张图片

 

;WITH Digits AS
(
    SELECT 0 AS digit
    UNION ALL
    SELECT digit + 1 FROM Digits where digit < 9
)
SELECT [digit],[dbo].[svf_IsEven]([digit]) AS [even],[dbo].[svf_IsOdd]([digit]) AS [odd] FROM Digits
Source Code

 

运行结果:

判断数字是否为奇数或偶数_第4张图片

 

你可能感兴趣的:(判断数字是否为奇数或偶数)