Friday, August 9, 2013

SQL Server - Executing Very long querys from a string

We have been linking out SQL servers to oracle lately as a mean of working around a particular issue which I will not go into. We have been needing to run oracle query from the linked server by wrapping the oracle queries in a string then using the 'EXECUTE (@query) AT [LINKED SERVER NAME'.

If the oracle query is less then 4000 characters the following would work:

declare @query as nvarchar(max)  =  '[a smaller then 4000 char oracle SQL] ' + '[Some more parts of the statement]'
EXECUTE (@query) AT [LINKEDSERVER]

Now as soon as the SQL statement is larger then 4000 characters you will begin to see errors when executing the statements. This is because when we concatenated the two strings in the above statement they concatenate into nvarchar(4000) in stead of nvarchar(max). To work around this issue cast all stings into nvarchar(max):

declare @query as nvarchar(max) = CAST('some sql' as nvarchar(max)) + CAST('some other sql' as nvarchar(max))
EXECUTE (@query) AT [LINKEDSERVER]
 

VoilĂ , we can now run excessively long queries from a string using EXECUTE.