# SQL语句实现水仙花数求取

2020-11-09 10:51:34

# SQL语句实现水仙花数求取

"水仙花数 "，所谓 "水仙花数 "是指一个三位数，其各位数字立方和等于该数本身。例如：370是一个 "水仙花数 "，因为 370=3 的三次方＋7的三次方＋0 的三次方

## 实现方法

### 方法一

CAST函数用于将某种数据类型的表达式显式转换为另一种数据类型，如：

``cast(substring(cast(@n as varchar(3)),1,1) as int``

``````declare @n int,@x as int,@y as int,@z as int
set @n=100
while @n<1000
begin
set @x=cast(substring(cast(@n as varchar(3)),1,1) as int)
set @y=cast(substring(cast(@n as varchar(3)),2,1) as int)
set @z=cast(substring(cast(@n as varchar(3)),3,1) as int)
if power(@x,3)+power(@y,3)+power(@z,3)=@n
begin
print @n
end
set @n=@n+1
end``````

### 方法二

``````declare @x int, @y int,@z int,@m int
set @x=1
set @y=0
set @z=0
while @x<10
begin
while @y<10
begin
while @z<10
begin
if power(@x,3)+power(@y,3)+power(@z,3)=(@x*100+@y*10+@z)
begin
select @m=@x*100+@y*10+@z
print @m
end
set @z=@z+1
end
set @y=@y+1
end
set @x=@x+1
end``````

``````declare @x int, @y int,@z int,@m int
set @x=1
set @y=0
set @z=0
while @x<10
begin
while @y<10
begin
while @z<10
begin
print @z
set @z=@z+1
end
set @y=@y+1
end
set @x=@x+1
end``````

``````declare @x int, @y int,@z int,@m int
set @x=1
while @x<10
begin
set @y=0
while @y<10
begin
set @z=0
while @z<10
begin
if power(@x,3)+power(@y,3)+power(@z,3)=(@x*100+@y*10+@z)
begin
select @m=@x*100+@y*10+@z
print @m
end
set @z=@z+1
end
set @y=@y+1
end
set @x=@x+1
end``````

https://my.oschina.net/u/4343506/blog/4708852