A lot of the time, DBAs are asked to run adhoc reports for various business people and, more often than not, the expected medium for these reports is Excel.
Now for the most part this seems simple enough…
- Run the T-SQL report
- Highlight the results
- Copy the results
- Paste into an Excel worksheet
How do you deal with carriage returns though? New line feeds? Tabs? Commas when you’re trying to comma delimit?
Try and copy them into an Excel worksheet and what you’re going to get is confusion, alarm, and vexation.
Not exactly the clear reporting that the business people are hoping for.
So what can we do? Panic? Grab another coffee? Roll your “r’s”?
Yes, yes, and not yet…
I have mentioned before that we can use CHAR(10) and CHAR(13) for new lines and carriage returns in SQL Server so I’ll leave it up to an exercise to the reader to create a table with these “troublesome” bits of information in them (plus if you came here from Google, I assume you already have a table with them in it).
For me, I’ve just created a single table
dbo.NewLineNotes that has a single entry with a new line in it.
So a straight-up copy and paste isn’t going to cut it here. If we have more than 1 row, we’re not going to get a 1 entry to 1 row in the report that we are looking for. How do people deal with this?
Well, depending on what tool you have, the answer could be as simple as a right-click and selecting “Open in Excel”
Let’s proceed with the impression that you do not have RedGate tools (cough free trial cough) and cannot avail of the right-click righteousness, what do you do then.
Well…have you thought about PowerShell?
Hear me out on this but you probably already have your query but found the new lines are screwing up the report. So let’s throw that query into a variable
$NewLineQuery = 'SELECT Notes FROM dbo.NewLineNotes'
Then what we have to do is somehow connect to the SQL Server instance and database.
Let’s go with the very basics here as that’s all we really need.
Invoke-SqlCmd, and yes I know it has problems. I’ve linked and talked about them before. It works for us in this situation though.
-ExpandPropertyand not just
-Property, or even why I included it at all.
-expandthen what we actually get is…
How does that help us with Reports?
If you work with PowerShell for the smallest amount of time, then I hope you’ve run into the command
Export-CSV. See help for details…
help Export-Csv -Full
This will output a delimited file (defaults to comma but we can change that if we want) to wherever we want. We can then open it up in Excel or whatever other tool you use.
Let’s see if that splits our information into a new line!
There are tons of different ways to do this but this is what I used.
Quick, dirty, and effective.
In the short term, I’m okay with that!