You have declared this as nvarchar(max) which allows 2GB of data so it will store 2GB.
What is happening:
- The datatype is not yet nvarchar(max) until assignment to @sql1
- Before that, it’s a collection of strings, each less than 4000 (constants)
- You are concatenating short constants with short variables (short = < 4000)
- So you have 4000 characters put into @sql1
So, you have make sure you have nvarchar(max) on the right hand side.
One idea. The 2nd line concatenates nvarchar(max) with a constant = nvarchar(max)
SET @SQL1 = ''
SET @SQL1 = @SQL1 + 'SELECT DISTINCT Venue...
....
It’s no different to the integer division that happens in every langauge.
declare @myvar float
set @myvar = 1/2 --gives zero because it's integer on the right
Operator precedence (infers datatype precedence) is always “assignment” last… why should unicode strings in SQL Server be any different?