提问人:JustinT 提问时间:1/17/2009 最后编辑:Jon SeigelJustinT 更新时间:4/19/2017 访问量:27385
T-SQL While 循环和串联
T-SQL While Loop and concatenation
问:
我有一个 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
脚本运行时,输出为 null,同时始终正确输出。是否有某种原因导致串联在 While 循环中不起作用?这似乎是错误的,因为递增效果很好。那么我还缺少什么吗?@tempCatString
@tempCat
@counter
答:
5赞
keithwarren7
1/17/2009
#1
这样会更有效率......
select @tempCatString = @tempCatString + Coalesce(Description,'') + '<br/>' from Categories...
select @fn
还可以将concat_null_yields_null视为解决串联问题的选项,尽管我会避免这种方式
7赞
HLGEM
1/17/2009
#2
看起来它应该可以工作,但由于某种原因,它似乎认为@tempCatString是空的,这就是为什么你总是得到一个空值,因为 null 连接到其他任何内容仍然是 null。建议您尝试对每个变量进行设置,如果它们为 null,则将它们设置为“ ”。COALESCE()
评论
0赞
JustinT
1/17/2009
我正在查询的表中的一个值是 null,因此将 IsNull() 添加到@tempCatString声明中解决了这个问题。谢谢
1赞
MatBailie
1/18/2009
#3
我同意 keithwarren 的观点,但我总是确保在查询中添加 ORDER BY 子句。然后,您可以确定这些值的确切连接顺序。
此外,将 NULL 值替换为 '' 的 COALESCE 将有效地生成空白行。我不知道你是否想要它们,但如果不是,只需过滤 WHERE 子句......
最后,您似乎有一个临时表,其中包含您感兴趣的 ID。此表可以包含在 JOIN 中以筛选源表...
DELCARE @output VARCHAR(8000)
SET @output = ''
SELECT
@output = @output + [Categories].Description + '<br/>'
FROM
Categories
INNER JOIN
#vals
ON #vals.val = [Categories].ID
WHERE
[Categories].Description IS NOT NULL
ORDER BY
[Categories].Description
上一个:while 语言
评论