判断数字是否为奇数或偶数
判断数字是否为奇数或偶数,可以参考下面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_IsOdd] ( @number INT ) RETURNS BIT AS BEGIN RETURN CASE WHEN @number % 2 <> 0 THEN 1 ELSE 0 END END GO
偶数:
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
举例说明:
;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
运行结果: