Search code examples
sqlsql-serversql-server-2008t-sqlvarchar

How to run a more than 8000 characters SQL statement from a variable?


I can use the following code for tiny little queries:

DECLARE @sql VARCHAR(8000)
SET @sql = 'SELECT * FROM myTable'
Exec @sql

The above method is very useful in order to maintain large amounts of code, especially when we need to make changes once and have them reflected everywhere.

My problem is my query (it's only one single query) that I want to feed into the @sql variable uses more than 25 table joins, some of them on temporary table variables, incorporates complex operations and it is hence much more than 8000 characters long.

I wished to use TEXT data type to store this query, but MSDN shows a warning message that Microsoft is planning to remove Text, NText and Image data types from their next versions. I wish my code to run in future too.

I thought of storing this query in a separate file, but as it uses joins on table variables and other procedure-specific parameters, I doubt if this is possible.

Kindly tell me a method to store a large query into a variable and execute it multiple times in a procedure.


Solution

  • If you are on SQL Server 2008 or newer you can use VARCHAR(MAX)

    DECLARE @sql VARCHAR(MAX)