Skip to content

Instantly share code, notes, and snippets.

@FARUK-YILDIRIM
Created June 12, 2024 06:39
Show Gist options
  • Select an option

  • Save FARUK-YILDIRIM/177a14a42ec008bf7afb6d998492bf5f to your computer and use it in GitHub Desktop.

Select an option

Save FARUK-YILDIRIM/177a14a42ec008bf7afb6d998492bf5f to your computer and use it in GitHub Desktop.
This script selects the top 3 rows of data from each table in the database whose names contain the letter "g".
DECLARE @TableName NVARCHAR(128)
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = ''
DECLARE table_cursor CURSOR FOR
SELECT name FROM sys.tables WHERE name LIKE '%g%';
OPEN table_cursor;
FETCH NEXT FROM table_cursor INTO @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = @SQL + 'SELECT TOP 3 ''' + @TableName + ''' AS TableName, * FROM ' + @TableName + '; '
FETCH NEXT FROM table_cursor INTO @TableName;
END;
CLOSE table_cursor;
DEALLOCATE table_cursor;
EXEC sp_executesql @SQL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment