Skip to content

Instantly share code, notes, and snippets.

@nikolay-pshenichny
Created September 15, 2015 01:17
Show Gist options
  • Save nikolay-pshenichny/8d35bd94a30d0e531505 to your computer and use it in GitHub Desktop.
Save nikolay-pshenichny/8d35bd94a30d0e531505 to your computer and use it in GitHub Desktop.
Fetch data from all tables (MS SQL)
declare @table_name varchar(200);
declare @table_object_id int;
declare @primary_key_column_name varchar(200);
declare all_tables cursor for select name, object_id from sys.tables order by name
open all_tables
fetch next from all_tables into @table_name , @table_object_id
while @@FETCH_STATUS = 0
begin
print '=============================='
print @table_name
print @table_object_id
select
@primary_key_column_name = col_name(idxcols.object_id, idxcols.column_id)
from sys.indexes idx
inner join sys.index_columns idxcols ON idx.object_id = idxcols.object_id AND idx.index_id = idxcols.index_id
where
idx.is_primary_key = 1
and idx.object_id = @table_object_id
print @primary_key_column_name
declare @query varchar(max) = 'select * from ' + @table_name + ' order by ' + @primary_key_column_name ;
print @query
exec(@query)
fetch next from all_tables into @table_name, @table_object_id
end
close all_tables
deallocate all_tables
go
sqlcmd -S %DB_SERVER% -d %DATABASE% -E -o output.txt -i fetch-data-from-all-tables.sql
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment