英文:
How do I make this code loop 7 times and go to the next row?
问题
I've been learning SQL by myself, and I'm stumped on this one.
In this table I'm working on, I have a persons first name and last name as a column, and I'm using a user-defined function to concatenate the two columns to get their full name.
What I have works for one column, but I don't know how to loop it. Here's my code.
创建函数 dbo.fullName(
@firstName VARCHAR(10),
@lastName VARCHAR(10))
返回 VARCHAR(20)
如
开始
声明 @fullName VARCHAR(20)
从 stray_kids 中选择 @fullName = CONCAT(firstName, ' ', lastName)
返回 @fullName;
结束
然后当我使用以下代码调用它时:
SELECT lastName, firstName, dbo.fullName(firstName, lastName) FROM stray_kids
它会生成我添加的图像,对于第一行非常好,然后我尝试添加 while 循环和计数器等,但是无法弄清楚。另外,如何命名新的列名?
谢谢,如果你可以帮助! <3 我的输出
英文:
I've been learning SQL by myself, and I'm stumped on this one.
In this table I'm working on, I have a persons first name and last name as a column, and I'm using a user defined function to concat the two columns to get their full name.
What I have works for one column, but I don't know how to loop it. Here's my code.
CREATE FUNCTION dbo.fullName(
@firstName VARCHAR(10),
@lastName VARCHAR(10))
RETURNS VARCHAR(20)
AS
BEGIN
DECLARE @fullName VARCHAR(20)
SELECT @fullName = CONCAT(firstName, ' ', lastName) FROM stray_kids
RETURN @fullName;
END
Then when I call it with SELECT lastName, firstName,dbo.fullName(firstName, lastName) FROM stray_kids
It comes up with the image I added, which is great for the first row and then I then tried to add a while loop and counters and such but couldn't figure it out. Also, how would I name the new column name?
Thanks if you can help! <3 my output
答案1
得分: 2
你需要的功能可以通过使用计算列轻松实现。
alter table stray_kids
add FullName as CONCAT(firstName, ' ', lastName);
然后你可以简单地执行:
select FullName from stray_kids;
SQL Server的较新版本还支持 concat_ws(' ', FirstName, LastName);
如果你真的想要使用一个函数,你只需要:
CREATE FUNCTION dbo.fullName(
@firstName VARCHAR(10),
@lastName VARCHAR(10))
RETURNS VARCHAR(21)
AS
BEGIN
RETURN CONCAT(@firstName, ' ', @lastName);
END
请注意返回类型需要考虑额外的空格字符... 10个字符似乎有点短,也许使用 varchar(50)
更合适。
英文:
The functionality you are after is easily achieved using a computed column
alter table stray_kids
add FullName as CONCAT(firstName, ' ', lastName);
Then you can simply
select FullName from stray_kids;
Newer versions of SQL Server also support concat_ws(' ', FirstName, LastName);
If you really wanted to use a function, all you need is
CREATE FUNCTION dbo.fullName(
@firstName VARCHAR(10),
@lastName VARCHAR(10))
RETURNS VARCHAR(21)
AS
BEGIN
RETURN CONCAT(@firstName, ' ', @lastName);
END
Note the return type needs to account for the additional space character... 10 chars seems al ittle short though so perhaps use varchar(50)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论