代码之家  ›  专栏  ›  技术社区  ›  JustinT

T-SQL while循环和连接

  •  1
  • JustinT  · 技术社区  · 17 年前

    我有一个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 输出为空,而 @tempCat 始终正确输出。在while循环中,串联是否有一些不起作用的原因?这似乎是错误的,因为 @counter 工作得很好。还有什么我不知道的吗?

    3 回复  |  直到 9 年前
        1
  •  4
  •   Shadow    9 年前

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

        2
  •  3
  •   keithwarren7    17 年前

    这会更有效……

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

    另外,请看concat_null_yield_null作为修复连接问题的选项,尽管我将避免该路由

        3
  •  1
  •   MatBailie    17 年前

    我同意Keithharren的观点,但我总是会在查询中添加一个ORDERBY子句。然后您可以确定值的连接顺序。

    此外,将空值替换为“”的合并将有效地生成空行。我不知道你是否需要它们,但如果不只是过滤在WHERE子句中…

    最后,您似乎有一个临时表,其中包含您感兴趣的ID。此表只能包含在联接中以筛选源表…

    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