gpt4 book ai didi

sql - T-SQL While 循环和串联

转载 作者:行者123 更新时间:2023-12-03 18:39:24 24 4
gpt4 key购买 nike

我有一个 SQL 查询,它应该提取一条记录并将每个记录连接到一个字符串,然后输出该字符串。查询的重要部分如下。

DECLARE @counter int;
SET @counter = 1;

DECLARE @tempID varchar(50);
SET @tempID = '';

DECLARE @tempCat varchar(255);
SET @tempCat = '';

DECLARE @tempCatString varchar(5000);
SET @tempCatString = '';

WHILE @counter <= @tempCount
BEGIN

SET @tempID = (
SELECT [Val]
FROM #vals
WHERE [ID] = @counter);

SET @tempCat = (SELECT [Description] FROM [Categories] WHERE [ID] = @tempID);
print @tempCat;

SET @tempCatString = @tempCatString + '<br/>' + @tempCat;
SET @counter = @counter + 1;

END

当脚本运行时, @tempCatString输出为 null 而 @tempCat始终正确输出。是否有某种原因使连接在 While 循环中不起作用?这似乎是错误的,因为递增 @counter完美地工作。那么还有什么我想念的吗?

最佳答案

看起来它应该可以工作,但出于某种原因,它似乎认为@tempCatString 为空,这就是为什么你总是得到一个空值,因为空连接到其他任何东西仍然是空。建议你试试 COALESCE()在每个变量上将它们设置为“”,如果它们为空。

关于sql - T-SQL While 循环和串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/451834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com