This week I had a user come to me asking about how fields were defined on a few tables he was using in writing some reports. Long story short, he’s been tasked with writing some new reports and updating existing ones, but he doesn’t have visibility to the database itself so he’s left with the “ok, let’s try this” approach and then reading error messages to debug when things go sideways. Very tedious.
I asked him for a list of the tables he was most interested in, and while he worked on that I set to work on (of course) a quick & dirty PowerShell script to collect the data he needed – field names, types, and whether they’re nullable.
With the help of
dbatools and Doug Finke’s
ImportExcel module, the resulting script to retrieve the requisite data and export it to an Excel workbook with one sheet per table is very short. Each table is on its own worksheet, with the header row bold and frozen so it stays in view while scrolling.
Line by line:
- Fetch the list of tables from a file provided to me
- Gather a collection of SMO objects for the tables from the server
- Loop over each table and extracting the relevant data about each
- Write the table’s information out to a worksheet named for the table in an Excel workbook
The only tricky part was fetching the field lengths for the
nvarchar fields. I had to go spelunking into each field’s
Properties property to get that. The result:
But I can tell this isn’t disco enough for you, so I’m gonna put it right here.
– Justin Hammer, Iron Man 2
You can do this in a one-liner too. It’s not as pretty, but it’s quite doable and the resulting Excel file is identical.
End to end, I turned this around in about 20 minutes and the the requestor’s life got easier in a big hurry. Best of all, when he comes back with another batch of tables for his next set of reports, I can turn the request around in less than five minutes.