I have a table variable with a column of type varchar(max). I am storing resultset of another query in this table variable. The length of the result that I get on querying this table is 7870. I wanted this result to be transposed using comma separator and before each value, I had to append "t." But this resulted in data exceeding 8000 so anything after that is getting truncated even if the datatype of the column is varchar(max)
Since datatype is varchar(max) so I don't want data to be truncated so tried setting property Set ANSI_WARNINGS OFF before inserting data to table variable But still no success.
DECLARE @FormattedMainResult VARCHAR(MAX)
DECLARE @CommonColumns TABLE (FinalColumns VARCHAR(MAX))
INSERT INTO @CommonColumns
SELECT main.AllColumnsMain AS CommonColumns
FROM [dbo].[Staging] Stg
INNER JOIN [dbo].[Target] main ON Stg.AllColumnsStg = main.AllColumnsMain
SELECT SUM(LEN(FinalColumns)) AS MaxLen_FinalCommonColumns
FROM @CommonColumns -- 7870
SELECT *
FROM @CommonColumns
Output:
Final Columns
---------------
John
Carl
Scott
Rick
SELECT @FormattedMainResult = (SELECT DISTINCT
STUFF((SELECT ',' + 't.' +u.FinalColumns
FROM
(SELECT FinalColumns
FROM @CommonColumns) u
FOR XML PATH('')), 1, 1, '') AS userlist)
SELECT SUM(LEN(@FormattedMainResult)) AS MaxLen_posttranspose -- 8230 so data is truncated
PRINT @FormattedMainResult
Output
t.John,t.Carl,t.Sc
Actual result from @FormattedMainResult:
t.John,t.Carl,t.Sc (data truncated)
Expected result from @FormattedMainResult:
t.John,t.Carl,t.Scott,....,t.Rick (no truncation)
Update
Now I am facing issue while executing Insert into statement which I get from select query result.
Example,
Declare @Result nvarchar(max)
DECLARE @FormattedStgResult varchar(MAX)
DECLARE @joinCondition VARCHAR(MAX)='s.Id=t.Id'
SET @Result = ''
SET @Result = 'INSERT INTO ' + QUOTENAME('vjtest') +'.'+ QUOTENAME('dbo') +'.'+ QUOTENAME('Staging') +' (' + @FormattedStgResult + ')
SELECT ' + @FormattedMainResult +
' FROM '+ QUOTENAME('vjtest') +'.'+ QUOTENAME('dbo')+'.'+QUOTENAME('Target') + ' t
LEFT JOIN '+ QUOTENAME('vjtest') +'.'+QUOTENAME('dbo')+'.'+QUOTENAME('Staging')+ ' s
ON ' + @joinCondition +
' WHERE s.UniqueId IS NULL'
Exec(@Result)
@FormattedMainResult is same as old code which will have values with prefix "t." -> t.Id,t.Name,1,....,t.Rootpid
@FormattedStgResult has the same result as @FormattedMainResult only difference there is no prefix "t." -> Id,Name,IsDelete,...Rootpid
This does generate correct Insert statement with expected columns but when it is executed in Exec(@Result) it says 0 rows affected. However, when that same query I execute manually it does show 3 rows affected.
QuoteName()to avoid problems with odd names, e.g.New Tablewith a space or reserved words likeFrom.QuoteName( u.FinalColumns )avoids surprises when getting column names from a possibly untrustworthy source, or just creatively named columns. ApplyingQuoteName()to'dbo'doesn't offer much benefit.