I am attempting to return all table results from each table in my database AdventureWorksDW2019. Would my current approach work somehow? Or is there more simple/efficient way to do this? In my current approach, I am storing all of the table names in a temp table with their respective row number when sorted by ascending name. Then, I am trying to wrap that in a WHILE statement to loop through each table and select all results from each table. Any advice would be greatly appreciated!
DROP TABLE IF EXISTS #TableNamesSorted
SELECT
name,
RowNum = ROW_NUMBER() OVER(ORDER BY name)
INTO #TableNamesSorted
FROM
SYSOBJECTS
WHERE
xtype = 'U'
DECLARE @i INT = 0;
DECLARE @currentTableName varchar(25);
WHILE @i < (SELECT COUNT(*) FROM #TableNamesSorted)
BEGIN
SET @i = @i + 1
SET @currentTableName = (SELECT name from #TableNamesSorted WHERE RowNum = @i)
SELECT * FROM (SELECT @currentTableName)
END
Incorrect syntax near the keyword 'END'is due to you did not assign an alias to the derived tableSELECT * FROM (SELECT @currentTableName)sp_executesqlwith a string fromSELECT STRING_AGG( CONCAT( 'SELECT * FROM ', TABLE_NAME, ';' ), CONCAT( CHAR(13), CHAR(10) ) ) FROM INFORMATION_SCHEMA.TABLESCONVERT( varchar(max), ): stackoverflow.com/questions/71355661/…