Hi Naomi Nosonovsky,
Thanks for reaching out SQL Q&A forum
You’re on the right track with building dynamic SQL, but the concatenation in your snippet is a bit off. The clean way to generate counts for all tables in schema rv is to use STRING_AGG with UNION ALL. Here’s a working example:
DECLARE @SQL NVARCHAR(MAX);
SET
@SQL = (
SELECT
STRING_AGG(
'SELECT ''' + t.table_name + ''' AS table_name, COUNT(*) AS row_count FROM rv.' + QUOTENAME(t.table_name),
' UNION ALL '
)
FROM
INFORMATION_SCHEMA.TABLES t
WHERE
t.TABLE_TYPE = 'BASE TABLE'
AND t.TABLE_SCHEMA = 'rv'
);
PRINT @SQL;
-- Run the generated SQL
EXEC sp_executesql @SQL;
Fixes:
STRING_AGG: Concatenates multiple rows into one string with a separator (UNION ALL here).
QUOTENAME: Safely wraps table names to avoid issues with special characters.
Aliasing: Added AS table_name so you know which table each count belongs to.
Execution: Use sp_executesql to run the dynamic SQL after building it.
Please ref Attached Screenshot
Hope This helps
Thanks,
Lakshmi.