【问题标题】:T-SQL While Loop and concatenationT-SQL While 循环和连接
【发布时间】:2010-10-01 21:32:41
【问题描述】:

我有一个 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 效果很好。那么我还有什么遗漏的吗?

【问题讨论】:

    标签: sql sql-server while-loop string-concatenation


    【解决方案1】:

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

    【讨论】:

    • 我正在查询的表中的一个值为 null,因此在 @tempCatString 声明中添加 IsNull() 可以解决问题。谢谢
    【解决方案2】:

    这样会更有效率....

    select @tempCatString = @tempCatString + Coalesce(Description,'') + '<br/>' from Categories...
    
    select @fn
    

    还可以将 concat_null_yields_null 作为解决串联问题的选项,尽管我会避免使用该路线

    【讨论】:

      【解决方案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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-07
        • 2016-12-22
        • 2021-03-23
        • 2013-07-12
        • 2010-09-14
        • 2012-02-26
        • 2016-03-30
        • 1970-01-01
        相关资源
        最近更新 更多