I'm trying to create a dynamic query that retrieves the columns of a table (as new columns might be added in the future) and this query might also be used on multiple databases with different table configurations.
The purpose right now is to compare if there are any changes in the values of the columns between OITM
and AITM
tables:
OITM
contains the current recordAITM
is a history table that contains the history records
AITM
and OITM
column structures are always the same except for the LogInstanc
column which only exists in the AITM
table:
DECLARE @ListOfColsValTabDel NVARCHAR(MAX) = '020650005'
DECLARE @SQL1 NVARCHAR(MAX)
SET @SQL1 = 'select COUNT(*) from OITM o
LEFT JOIN AITM a on o."ItemCode" = a."ItemCode"
and a."LogInstanc" = (Select
Max(x."Loginstanc")
from AITM x
where x."ItemCode" =''' + @ListOfColsValTabDel
+'''
)
WHERE o."ItemCode" = '''+ @ListOfColsValTabDel
+ ''' AND ('
-- Below Sub query returns string of 9975
+
(select LEFT (REPLACE(stuff((SELECT 'o.'+Name + ' <> a.'+ Name + ' or ' FROM sys.columns WHERE object_id = OBJECT_ID('dbo.OITM') FOR XML PATH('')), 1, 0, '') , '<>','<>')
,LEN(REPLACE(stuff((SELECT 'o.'+Name + ' <> a.'+ Name + ' or ' FROM sys.columns WHERE object_id = OBJECT_ID('dbo.OITM') FOR XML PATH('')), 1, 0, '') , '<>','<>')) - 3))
+')'
PRINT (@SQL1) -- Gets truncated at 4000 characters
--exec(@SQL1)
This prints 4000 characters while the total string should be around 11000 as the sub query for retrieving the columns is already 9975 characters.
I know you can execute dynamic SQL with (@SQL1 4000 characters + @SQL2 4000 characters + SQL 3 4000 characters).
But how to split this string up in variables of 4000 characters?
An alternative method people mention is to cast the string as NVARCHAR(MAX) but this didn't seem to help either.