我需要编写一个查询来打印所有小于或等于 1000 的素数。我需要将结果打印到一行中并使用 & 字符作为分隔符(而不是空格)。像这样:
2&3&5&7&11&13
这是我的代码(Number 的数据类型是 int,所以我需要将其更改为 varchar,以便与号字符可以与 Number 一起显示在一个单元格中):
with temp as
(select 2 as Number
union all
select Number + 1 from temp where Number<1000)
, temptwo as
(select * from temp t1
where NOT EXISTS
(select 1 from temp t2
where t1.Number > t2.Number
and t1.Number % t2.Number = 0))
, tempthree as
(select Cast(Number AS Varchar) as Number from temptwo)
select
STUFF((SELECT '&' + Number
FROM tempthree tt
WHERE tt.Number = t.Number
FOR XML PATH('')), 1, 1, '')
FROM tempthree t
OPTION (MAXRECURSION 0)
但它并没有真正起作用。我不知道是什么问题?到目前为止,它运行良好:
with temp as
(select 2 as Number
union all
select Number + 1 from temp where Number<1000)
, temptwo as
(select * from temp t1
where NOT EXISTS
(select 1 from temp t2
where t1.Number > t2.Number
and t1.Number % t2.Number = 0))
select Cast(Number AS Varchar) as Number from temptwo
OPTION (MAXRECURSION 0)
但它只打印出如下内容:
2
3
5
7
11
13
...
但这不是我想要的。任何人都可以帮忙吗?