在迭代循环中连接字符串:+ =不能按预期工作

时间:2013-01-12 16:10:44

标签: sql-server tsql temp-tables

我有本地表和字符串,必须从其值填充:

    DECLARE @#SomeTable  TABLE ( some columns ..)
    DECLARE @SomeString  varchar(8000) = 'init string'

迭代时

    WHILE EXISTS(SELECT * FROM  @#SomeTable)
     BEGIN
        // [somecolumn] is declared temp variable
        SELECT TOP 1 @somecolumn = somecolumn FROM  @#SomeTable

        PRINT 'before ' + @SomeString // 'init string'
        PRINT [some values from SomeTable]  // this OK
        SET @SomeString += [some values from SomeTable] 
        PRINT 'after ' +  @SomeString //'init string' UPDATE NOT TAKE PLACE!!!!

        DELETE  @#SomeTable Where somecolumn = @somecolumn
     END

我发现连接失败了。为什么呢?

编辑:

这是一段原始代码:

    /*Represents [WHERE] clause for retrieving values from specifyed range*/
DECLARE @WHEREclause nchar(1000) = 'WHERE '
/*Represents [ORDER BY] clause for sorting in right order and direction {ASC|DESC}*/
DECLARE @ORDERBYclause nchar(1000) = 'ORDER BY '
/*Dynamic query that returns end result*/
DECLARE @sqlCmd varchar(8000) = 
'SELECT 
        img,
        capacity,
        price,
        Id
 FROM HDD  '
/* -a- filling table for input values*/
INSERT INTO @#SequenceTable(columnName,columnValue,comparator,isASC,columnOrder)
SELECT 
    columnName,
    columnValue,
    comparator,
    isASC,
    ROW_NUMBER() OVER (ORDER BY  outOrder) AS columnOrder
FROM
(
        SELECT 'buffer' as columnName, CAST(@buffer AS nchar(20)) as columnValue, @bufferCmp as comparator, @bufferASC as isASC, @bufferOrder as outOrder
    UNION  
        SELECT 'capacity', CAST(@capacity AS nchar(20)), @capacityCmp, @capacityASC, @capacityOrder  
    UNION  
        SELECT 'price', STR(@price,20,2),  @priceCmp, @priceASC, @priceOrder
    UNION  
        SELECT 'angle_speed', CAST(@angleSpeed AS nchar(20)), @angleSpeedCmp ,@angleSpeedASC,@angleSpeedOrder
) AS AnyName
ORDER BY columnOrder 

/*---/a-----------------------------------------------------------------------------------*/

/*variables for above fields*/
DECLARE @columnName nchar(20)
DECLARE @comparator char
DECLARE @columnValue nchar(20)
DECLARE @isASC char

WHILE EXISTS(SELECT * FROM  @#SequenceTable)
BEGIN

    SELECT TOP 1 @columnName = columnName FROM  @#SequenceTable
    SELECT TOP 1 @comparator = comparator FROM  @#SequenceTable 
    SELECT TOP 1 @columnValue = columnValue FROM  @#SequenceTable 
    SELECT TOP 1 @isASC = isASC FROM  @#SequenceTable 

    IF @WHEREclause != 'WHERE '
        BEGIN
            SET @WHEREclause += ' AND '
        END
    PRINT 'before ' + @WHEREclause
    PRINT CONCAT(RTRIM(@columnName), @comparator, @columnValue)
    SET @WHEREclause += CONCAT(RTRIM(@columnName), @comparator, @columnValue)
    PRINT 'after ' +  @WHEREclause

    IF @ORDERBYclause != 'ORDER BY '
        BEGIN
            SET @ORDERBYclause += ','
        END
    IF @isASC = '1'
       SET @ORDERBYclause += CONCAT(RTRIM(@columnName),' ASC ')
    ELSE
       SET @ORDERBYclause += CONCAT(RTRIM(@columnName),' DESC ')

    Delete  @#SequenceTable Where columnName = @columnName

END

这是打印结果:

        before WHERE 
        angle_speed=7400 
        after WHERE 

+=无效。如果我使用

@SomeString = 'some value' 

然后更新可见,但如果我改为使用

@SomeString += 'some value' 

更新不可见

3 个答案:

答案 0 :(得分:9)

我可以向您保证,SQL Server中没有错误,并且+=完全按预期工作。我尝试了以下代码:

SET NOCOUNT ON;

DECLARE @#SomeTable TABLE (somecolumn VARCHAR(8000));

INSERT @#SomeTable VALUES('a'), ('bbb'), ('ccccc');

DECLARE @SomeString  varchar(8000) = 'init string',
        @somecolumn  varchar(8000);

WHILE EXISTS (SELECT * FROM  @#SomeTable)
BEGIN
    SELECT TOP 1 @somecolumn = somecolumn FROM @#SomeTable;

    SET @SomeString += @somecolumn;

    PRINT @SomeString; -- Works fine!!!

    DELETE  @#SomeTable Where somecolumn = @somecolumn;
END

以下是我的结果:

init stringa
init stringabbb
init stringabbbccccc

由于无法确切地告诉你在代码中做了什么(你已经混淆了最重要的部分),也许你可以从那里开始?当然,您在表中有一个NULL值,或者您分配错误,或者您正在分配错误的变量。再说一遍,无法分辨,因为你隐藏了代码的关键部分!

此外,由于您似乎并不关心订单,因此您也可以在不循环的情况下执行此操作:

SET NOCOUNT ON;

DECLARE @#SomeTable TABLE (somecolumn VARCHAR(8000));

INSERT @#SomeTable VALUES('a'), ('bbb'), ('ccccc');

DECLARE @SomeString  varchar(8000) = 'init string',
        @somecolumn  varchar(8000);

SELECT @SomeString += somecolumn FROM @#SomeTable;

PRINT @SomeString;

结果:

init stringabbbccccc

如果您关心顺序,您仍然可以在不循环的情况下执行此操作 - 使用XML技巧按顺序连接,然后将其附加到init字符串:

SET NOCOUNT ON;

DECLARE @#SomeTable TABLE (somecolumn VARCHAR(8000));

INSERT @#SomeTable VALUES('a'), ('bbb'), ('ccccc');

DECLARE @SomeString  varchar(8000) = 'init string',
        @somecolumn  varchar(8000) = '';

SELECT @somecolumn = (SELECT somecolumn FROM @#SomeTable
ORDER BY somecolumn DESC
FOR XML PATH, TYPE).value('.[1]', 'nvarchar(max)');

PRINT @SomeString + @somecolumn;

结果:

init stringcccccbbba

答案 1 :(得分:7)

如果涉及的值之一为NULL,则SQL Server中两个值之间的任何计算都会导致NULL。在您的情况下,@SomeString未初始化。这意味着它的值为NULL。因此SET @SomeString =+ 'somevalue'会产生NULL

要解决此问题,请在开头将变量初始化为''

此外,您还有以下代码:

SET @somecolumn += [some values from SomeTable]

但你可能想要这样:

SET @SomeString += [some values from SomeTable]

答案 2 :(得分:1)

我遇到了同样的问题,这肯定是T-SQL的一个已知问题。这里将详细解释:https://marc.durdin.net/2015/07/concatenating-strings-in-sql-server-or-undefined-behaviour-by-design/

总结:

使用SELECT语句的变量赋值是一种专有语法(仅限T-SQL),如果生成多行,则行为未定义或依赖于计划。

在具有ORDER BY子句的查询中使用赋值操作(在此示例中为连接)具有未定义的行为。由于查询计划的更改,这可能会在不同版本之间或甚至在特定服务器版本中发生变化。即使有解决方法,也不能依赖此行为。

唯一有保障的机制如下: 1.使用游标按特定顺序循环遍历行并连接值 2.使用ORDER BY进行xml查询以生成连接值 3.使用CLR聚合(这不适用于ORDER BY子句)