User defined function with while loop in SQL Server(SQL Server 中带有 while 循环的用户定义函数)
问题描述
我被要求在 SQL Server 中创建一个用户定义的函数以返回以下模式(例如,如果输入 = 5):
I am asked to create a user defined function in SQL Server to returns the following pattern (for example, if the input = 5):
*****
****
***
**
*
这是我的代码:
alter function udf_star (@input int)
returns varchar (200)
as
begin
declare @star int
set @star = @input
declare @space int
set @space = 0
while @star > 0
begin
declare @string varchar (200)
set @string = replicate (' ', @space) + replicate ('*', @star)
set @star = @star - 1
set @space = @space + 1
end
return @string
end
当我执行函数时
select dbo.udf_star (5)
它只显示
' *'
(4 个空格 + 1 颗星);谁能指出我应该如何更正语法?
(4 spaces + 1 star); can anyone points out how should I correct the syntax?
提前致谢!
推荐答案
看来您可能想要一个表值函数.
It seems you may want a Table-Valued Function.
此外,应尽可能避免循环
Also, loops should be avoided when possible
示例
CREATE FUNCTION [dbo].[tvf-Star] (@Input int)
Returns Table
As
Return (
Select Top (@Input)
Stars = replicate(' ',@Input-N)+replicate('*',N)
From ( Select Top (@Input) N=Row_Number() Over (Order By (Select NULL)) From master..spt_values n1 ) A
Order By N Desc
)
如果您要:
Select * from [dbo].[tvf-Star](5)
结果
Stars
*****
****
***
**
*
这篇关于SQL Server 中带有 while 循环的用户定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server 中带有 while 循环的用户定义函数
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
