Trouble with Dynamic T-SQL IIF Statement

2019-07-23 23:23发布

问题:

This code works fine and does exactly what I want, which is to sum the Qty * Price for each instance of the dynamic query.

But when I add an IIF statement it breaks. What I am trying to do is the same thing as above but when the transaction type is 'CO' set the sum to a negative amount.

回答1:

The problem turned out to be the NVARCHAR(4000) type of @sql, limiting its length to 4000 characters: the query got truncated at some random place after adding another long chunk to it.

DECLARE @sql NVARCHAR(MAX) solves the problem, allowing a dynamic query of any size below 2GB.