I have a database with dynamically generated tables. I’m writting a stored procedure to execute queries over the generated tables and I need to see the results in the query analyzer tool (or alike).
What I currently have is:
DECLARE @TableName sysname
DECLARE TableNameCursor CURSOR FOR
SELECT TableName FROM [xxxTables] WHERE xxx...
OPEN TableNameCursor
FETCH NEXT FROM TableNameCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @Query nvarchar
SET @Query = 'SELECT * FROM ' + @TableName
EXEC sp_executesql @Query
-- This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM TableNameCursor INTO @TableName
END
But as I have multiple selects I’m not getting the output. How can I fix the stored procedure to show the result?
All the tables have the same layout so I can join them.
Unless this is merely a typo produced when posting the script here, I might have finally found the issue. You haven’t specified the maximum length for the
@Queryvariable:In this context the maximum length defaults to
1, as per the manual:When you are assigning a query string to
@Query, it only stores the first character. Naturally, when you are later trying to execute the query, it returns nothing and should produce an error instead.You can fix it by specifying a maximum length. In SQL Server 2005 or later version, it could be an explicit number (up to 4000) or
max:In earlier versions
maxis not supported, so just use an explicit number: