我觉得自己很愚蠢,因为我可以轻松地在java或C#中使用for循环执行此操作,但我是SQL的新手,我无法解决这个问题。到目前为止,我已经为我想要找到共同因子的数字声明了两个整数变量。然而,根据我正在阅读的SQL,我需要使用while循环来循环数字以找到常见因素,我是否在正确的轨道上?之后我只想让SQL服务器打印常见因素。这是我到目前为止的代码......
DECLARE @num1 int = 10;
DECLARE @num2 int = 20;
DECLARE @count INT = 1;
WHILE @count < @num1
BEGIN
IF (@num % @count = ?)
PRINT 'common factors'
END
我在这里至少走在正确的轨道上吗? 在此先感谢您的任何帮助
答案 0 :(得分:1)
尝试没有循环的这个:
declare @num1 int
declare @num2 int
declare @f varchar(4000)
select @num1 = 12, @num2 = 26, @f = ''
;with lv0 as (select 0 g union all select 0)
,lv1 as (select 0 g from lv0 a cross join lv0 b) -- 4
,lv2 as (select 0 g from lv1 a cross join lv1 b) -- 16
,lv3 as (select 0 g from lv2 a cross join lv2 b) -- 256
,tally (n) as (select row_number() over (order by (select null)) from lv3)
select @f = @f + ', ' + convert(varchar(4000),n)
from tally
where
n <= @num1
and @num1 % n = 0
and @num2 % n = 0
print stuff(@f, 1, 2, '')
答案 1 :(得分:0)
谢谢大家,user3530547链接帮助我解决了问题。我保持循环并使用它...
USE md0577283
DECLARE @num1 int = 10;
DECLARE @num2 int = 20;
DECLARE @count INT = 1;
WHILE @count < @num1
BEGIN
IF (@num1 % @count = 0 and @num2 % @count = 0)
PRINT @count
set @count = @count + 1
END