edit query to add column to show table name in each record result: DECLARE @sql…
- User
edit query to add column to show table name in each record result:
DECLARE @sql NVARCHAR(MAX) = '';
-- Loop through the table numbers from 140 to 300 DECLARE @i INT = 230;
WHILE @i <= 300 BEGIN DECLARE @tableName NVARCHAR(255) = 'dbo.f' + CAST(@i AS NVARCHAR(10));
code-- Check if the table exists and if the 'cod' column exists in that table IF OBJECT_ID(@tableName, 'U') IS NOT NULL AND EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'f' + CAST(@i AS NVARCHAR(10)) AND COLUMN_NAME = 'cod') BEGIN -- Assuming you want to select all columns; you can specify column names if needed SET @sql += 'SELECT * FROM ' + @tableName + ' WHERE cod = 307 UNION ALL '; END SET @i += 1;END
-- Remove the last UNION ALL if any tables were found IF LEN(@sql) > 0 BEGIN -- Remove the trailing ' UNION ALL ' SET @sql = LEFT(@sql, LEN(@sql) - LEN(' UNION ALL '));
code-- Execute the dynamic SQL if there were tables found EXEC sp_executesql @sql;END ELSE BEGIN PRINT 'No tables found with cod = 307'; END
- Assistant
To modify your SQL query to include the table name in each record of the result set, you can add a column that specifies the table name in each
SELECTstatement. Here's your updated SQL script:sql