老sql上有点生锈。
你能帮忙吗?
给定一个数字,例如1或2或4,我需要确定它是偶数还是奇数并进行一些计算 取决于偶数还是奇数。
如何在sql(sql server 2000)中检测到 非常感谢
答案 0 :(得分:47)
使用模数运算符n % 2
。如果数字是偶数,则返回0;如果数字是奇数,则返回1.
答案 1 :(得分:7)
你也可以使用sql server BIT WISE操作符
DECLARE @Int INT
SELECT @Int = 103
SELECT @Int & 1, @Int % 2
答案 2 :(得分:5)
声明@t table(num int) 插入@t select 1 union all select 2 union all select 3 union all select 4
select
num
,case when num % 2 = 0 then 'Even' else 'Odd' end as Status
from @t
输出:
num状态
1 Odd
2 Even
3 Odd
4 Even
e.g。如果数字是偶数(乘以1)或奇数(乘以2),则除以10得到余数
declare @myNumber int ,@result int
set @myNumber = 16
select
Result =
(case when @myNumber % 2 = 0 then @myNumber * 1 else @myNumber * 2 end) %10
<强>结果强>
6
当@myNumber = 11
然后
<强>结果强>
2
希望这有帮助
答案 3 :(得分:4)
我在MS SQL SP中使用相同的东西如下:
IF @current_number % 2 = 0 SET @something = 1
- 或 -
IF @current_number % 2 = 0 exec sp_whatever
答案 4 :(得分:2)
答案 5 :(得分:1)
让我们说桌子STATION。
架构:
ID NUMBER
CITY VARCHAR
STATE VARCHAR
You can use any of the mentioned criteria to fetch the even ID.
1. MOD() Fucntion
select distinct CITY from STATION as st where MOD(st.id, 2) = 0
2. % function
select distinct CITY from STATION as st where st.id % 2 = 0
答案 6 :(得分:0)
您可以检查该数字的十六进制值的1位。如果该位打开,则为奇数。
DECLARE @Int INT
SELECT CASE WHEN @Int&0x0001<>0 THEN 'ODD' ELSE 'EVEN' END
答案 7 :(得分:0)
不打算作为严重的答案...但是可以工作。
请保留以下内容,供不喜欢的人(他们想要作弊的人)提供给您不喜欢的人,他们只想快速回答。
--Enter the whole integer you want to check
declare @number int = 115
--The check is independent of sign
set @number = abs(@number)
declare @OriginalNumber int = @number
--Firstly, we need to peform the Wilhelm Leibniz conversion, 64 length to allow for very big numbers
declare @WilhelmLeibnizConversion varchar(64) = ''
declare @currentBit int = power(8,exp(log(1))+1)
while @currentBit > 0
begin
set @WilhelmLeibnizConversion=convert(char(1), @number % 2) + @WilhelmLeibnizConversion
set @number = convert(int, (@number / 2))
set @currentBit-=1
end
--Although checking the 1 bit value of the Wilhelm Leibniz conversion is usually enough, for robust code you should also include the Kimmo Eriksson Factors one and two.
declare @KimmoErikssonFactor1 int = (@OriginalNumber + 1) % 2
declare @KimmoErikssonFactor2 int = (@OriginalNumber - 1) & 1
--Now check all 3 for 100% confirmation on the parity of your original number.
select case when right(@WilhelmLeibnizConversion,1) = 0 and (@KimmoErikssonFactor1 + @KimmoErikssonFactor2 <> 0) then 'Even' else 'Odd' end
答案 8 :(得分:0)
%
运算符检索模数,因此检查除以2的模数就可以知道它是奇数还是偶数。
DECLARE @i int =1;
while @i <= 20
begin
if @i % 2 = 0
PRINT @i
IF @i = 10 PRINT 'halfway there!';
set @i = @i+1;
end
答案 9 :(得分:-1)
USE AdventureWorks;
GO
SELECT BusinessEntityID,
CASE BusinessEntityID % 2
WHEN 0 THEN 'Even' ELSE 'Odd' END AS "Status"
FROM HumanResources.Employee;
GO