Share via

T-SQL is returning unexpected results

Keith Dimmock 20 Reputation points
2023-11-16T21:00:09.53+00:00

the following w queries return different results:

 declare @sql nvarchar(max)
 declare @id int = 15
 SET @SQL = '';

							
SELECT @SQL = @SQL + AlterTableSQL  
FROM CustomRegisters_CustomFields
WHERE LogId = @id
        AND ISNULL(AlterTableSQL, '') <> ''
ORDER BY Id;
 
select @sql

and

 declare @sql nvarchar(max)
 declare @id int = 15
 SET @SQL = '';

							
SELECT @SQL = @SQL + AlterTableSQL  
FROM CustomRegisters_CustomFields
WHERE LogId = 15
        AND ISNULL(AlterTableSQL, '') <> ''
ORDER BY Id;
 
select @sql

the only difference is changing a variable to a constant

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

Dan Guzman 9,516 Reputation points
2023-11-16T23:17:45.34+00:00

I see from your comment you're stuck in the pre-SQL 2017 world where STRING_AGG is not an option. In that case, use FOR XML instead for defined behavior:

SELECT @SQL = (SELECT COALESCE(AlterTableSQL,'')  
	FROM CustomRegisters_CustomFields
	WHERE LogId = @id
	ORDER BY id
FOR XML PATH(''), TYPE).value('(./text())[1]', 'NVARCHAR(MAX)');

SELECT @SQL;
GO

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Dan Guzman 9,516 Reputation points
    2023-11-16T22:51:22.3666667+00:00

    Aggregate string concatenation behavior (e.g. @SQL = @SQL + ...) is undefined. Use STRING_AGG instead, which will work consistently regardless of the execution plan and simplify the query too since you can omit the ISNULL expression.

    DECLARE @sql nvarchar(MAX);
    DECLARE @id int = 15;
    							
    SELECT @SQL = STRING_AGG(AlterTableSQL,'') WITHIN GROUP (ORDER BY id)
    FROM CustomRegisters_CustomFields
    WHERE LogId = @id;
     
    SELECT @sql;
    

    Was this answer helpful?

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.