The Hunter - Sheldon Allan Silverstein (1930-?)  

Posted by ReelTym

I have fought against the poodle with his gory, deadly paws;
I have faced the fearsome kitten, wild and bony,
And somehow I've evaded the enormous chomping jaws
Of the frighteningly ferocious Shetland pony.

My triumph o'er the rabbit is now sung throughout the land,
And men still speak in whispers of the day
When, attacked by twelve mosquitoes, with my one unwounded hand,
I killed nine of them and drove the rest away.

I have faced the housefly in his lair, I have stalked the ladybug
And the caterpillar, grim and fierce and hairy;
That trophy there is bumblebee, and this, my favourite rug,
Has been fashioned from the hide of a canary.

I have dove into the ocean to do combat with a shrimp,
I have dared the hen to come on out and fight;
I have battled with the butterfly (that's why I have this limp),
And I slew a monstrous grubworm just last night.

But this evening I must sally forth to meet the savage moth,
And if I don't come back in time for tea,
You shall know that I fell gallantly, as gallantly I fought
So please be gentle when you speak of me.

About Boys - Edgar Albert Guest (1881-1959)  

Posted by ReelTym

Show me the boy who never threw
A stone at someone's cat;
Or never hurled a snowball swift
At someone's high silk hat.
Who never ran away from school,
To seek the swimming hole;
Or slyly from a neighbor's yard
Green apples never stole.
Show me the boy who never broke
A pane of window glass;
Who never disobeyed the sign
That says: "Keep off the grass."
Who never did a thousand things,
That grieve us sore fo tell;
And I'll show you a little boy
Who must be far from well.

His Apologies - Rudyard Kipling (1865-1936)  

Posted by ReelTym

This took me a couple verses to realize it was a prayer about a dog.

Master, this is Thy Servant. He is rising eight weeks old.
He is mainly Head and Tummy. His legs are uncontrolled.
But Thou hast forgiven his ugliness, and settled him on Thy knee . . .
Art Thou content with Thy Servant? He is very comfy with Thee.

Master, behold a Sinner? He hath committed a wrong.
He hath defiled Thy Premises through being kept in too long.
Wherefore his nose has been rubbed in the dirt, and his self-respect has been bruiséd.
Master, pardon Thy Sinner, and see he is properly looséd.

Master — again Thy Sinner! This that was once Thy Shoe,
He hath found and taken and carried aside, as fitting matter to chew.
Now there is neither blacking nor tongue, and the Housemaid has us in tow.
Master, remember Thy Servant is young, and tell her to let him go!

Master, extol Thy Servant! He hath met a most Worthy Foe!
There has been fighting all over the Shop — and into the Shop also!
Till cruel umbrellas parted the strife (or I might have been choking him yet).
But Thy Servant has had the Time of his Life — and now shall we call on the vet?

Master, behold Thy Servant! Strange children came to play,
And because they fought to caress him, Thy Servant wentedst away.
But now that the Little Beasts have gone, he has returned to see
(Brushed — with his Sunday collar on) what they left over from tea.

Master, pity Thy Servant! He is deaf and three parts blind,
He cannot catch Thy Commandments. He cannot read Thy Mind.
Oh, leave him not in his loneliness; nor make him that kitten’s scorn.
He hath had none other God than Thee since the year that he was born!

Lord, look down on Thy Servant! Bad things have come to pass,
There is no heat in the midday sun, nor health in the wayside grass.
His bones are full of an old disease — his torments run and increase.
Lord, make haste with Thy Lightnings and grant him a, quick release!

The 'Ole In The Ark - Marriott Edgar (1880-1951)  

Posted by ReelTym

One evening at dusk as Noah stood on his Ark,
Putting green oil in starboard side lamp,
His wife came along and said, 'Noah, summat's wrong,
Our cabin is getting quite damp.

Noah said, 'Is that so?' Then he went down below,
And found it were right what she'd said,
For there on the floor quite a puddle he saw,
It was slopping around under t' bed.

Said he, 'There's an 'ole in the bottom somewhere,
We must find it before we retire.'
Then he thowt for a bit, and he said 'Aye, that's it,
A bloodhound is what we require.'

Se he went and fetched bloodhound from place where it lay,
'Tween the skunk and the polecat it were,
And as things there below, were a trifle so-so,
It were glad of a breath of fresh air.

They followed the sound as it went sniffing round,
'Til at last they located the leak,
'Twere a small hole in the side, about two inches wide,
Where a swordfish had poked in its beak.

And by gum! how the wet squirted in through that hole,
Well, young Shem who at sums was expert,
Worked it out on his slate that it came at the rate,
Of per gallon, per second, per squirt.

The bloodhound tried hard to keep water in check,
By lapping it up with his tongue,
But it came in so fast through that hole, that at last,
He shoved in his nose for a bung.

The poor faithful hound, he were very near drowned,
They dragged him away none too soon,
For the stream as it rose, pushed its way up his nose,
And blew him up like a balloon.

And then Mrs Noah shoved her elbow in t'hole,
And said,' Eh! it's stopped I believe,'
But they found very soon as she'd altered her tune,
For the water had got up her sleeve.

When she saw as her elbow weren't doing much good,
She said to Noah, 'I've an idea,
You sit on the leak and by t'end of the week,
There's no knowing, the weather may clear.'

Noah didn't think much to this notion, at all,
But reckoned he'd give it a try,
On the 'ole down he flopped, and the leaking all stopped,
And all… except him, was quite dry.

They took him his breakfast and dinner and tea,
As day after day there he sat,
'Til the rain was all passed and they landed at last,
On top side of Mount Ararat.

And that is how Noah got them all safe ashore,
But ever since then, strange to tell,
Them as helped save the Ark has all carried a mark,
Aye, and all their descendants as well.

That's why dog has a cold nose, and ladies cold elbows,
You'll also find if you enquire,
That's why a man takes his coat tails in hand,
And stands with his back to the fire.

The Cremation of Sam McGee - Robert Service (1874-1958)  

Posted by ReelTym

There are strange things done in the midnight sun
By the men who moil for gold;
The Arctic trails have their secret tales
That would make your blood run cold;
The Northern Lights have seen queer sights,
But the queerest they ever did see
Was that night on the marge of Lake Lebarge
I cremated Sam McGee.

Now Sam McGee was from Tennessee, where the cotton blooms and blows.
Why he left his home in the South to roam 'round the Pole, God only knows.
He was always cold, but the land of gold seemed to hold him like a spell;
Though he'd often say in his homely way that "he'd sooner live in hell."

On a Christmas Day we were mushing our way over the Dawson trail.
Talk of your cold! through the parka's fold it stabbed like a driven nail.
If our eyes we'd close, then the lashes froze till sometimes we couldn't see;
It wasn't much fun, but the only one to whimper was Sam McGee.

And that very night, as we lay packed tight in our robes beneath the snow,
And the dogs were fed, and the stars o'erhead were dancing heel and toe,
He turned to me, and "Cap," says he, "I'll cash in this trip, I guess;
And if I do, I'm asking that you won't refuse my last request."

Well, he seemed so low that I couldn't say no; then he says with a sort of moan:
"It's the cursèd cold, and it's got right hold, till I'm chilled clean through to the bone.
Yet 'tain't being dead — it's my awful dread of the icy grave that pains;
So I want you to swear that, foul or fair, you'll cremate my last remains."

A pal's last need is a thing to heed, so I swore I would not fail;
And we started on at the streak of dawn; but God! he looked ghastly pale.
He crouched on the sleigh, and he raved all day of his home in Tennessee;
And before nightfall a corpse was all that was left of Sam McGee.

There wasn't a breath in that land of death, and I hurried, horror-driven,
With a corpse half hid that I couldn't get rid, because of a promise given;
It was lashed to the sleigh, and it seemed to say: "You may tax your brawn and brains,
But you promised true, and it's up to you, to cremate those last remains."

Now a promise made is a debt unpaid, and the trail has its own stern code.
In the days to come, though my lips were dumb, in my heart how I cursed that load.
In the long, long night, by the lone firelight, while the huskies, round in a ring,
Howled out their woes to the homeless snows — Oh God! how I loathed the thing.

And every day that quiet clay seemed to heavy and heavier grow;
And on I went, though the dogs were spent and the grub was getting low;
The trail was bad, and I felt half mad, but I swore I would not give in;
And I'd often sing to the hateful thing, and it hearkened with a grin.

Till I came to the marge of Lake Lebarge, and a derelict there lay;
It was jammed in the ice, but I saw in a trice it was called the "Alice May."
And I looked at it, and I thought a bit, and I looked at my frozen chum;
Then "Here," said I, with a sudden cry, "is my cre-ma-tor-eum."

Some planks I tore from the cabin floor, and I lit the boiler fire;
Some coal I found that was lying around, and I heaped the fuel higher;
The flames just soared, and the furnace roared — such a blaze you seldom see;
And I burrowed a hole in the glowing coal, and I stuffed in Sam McGee.

Then I made a hike, for I didn't like to hear him sizzle so;
And the heavens scowled, and the huskies howled, and the wind began to blow.
It was icy cold, but the hot sweat rolled down my cheeks, and I don't know why;
And the greasy smoke in an inky cloak went streaking down the sky.

I do not know how long in the snow I wrestled with grisly fear;
But the stars came out and they danced about ere again I ventured near;
I was sick with dread, but I bravely said: "I'll just take a peep inside.
I guess he's cooked, and it's time I looked"; ... then the door I opened wide.

And there sat Sam, looking cool and calm, in the heart of the furnace roar;
And he wore a smile you could see a mile, and said: "Please close that door.
It's fine in here, but I greatly fear, you'll let in the cold and storm —
Since I left Plumtree, down in Tennessee, it's the first time I've been warm."

There are strange things done in the midnight sun
By the men who moil for gold;
The Arctic trails have their secret tales
That would make your blood run cold;
The Northern Lights have seen queer sights,
But the queerest they ever did see
Was that night on the marge of Lake Lebarge
I cremated Sam McGee.

The Owl Critic - James Thomas Fields (1817-1881)  

Posted by ReelTym

"Who stuffed that white owl?" No one spoke in the shop,
The barber was busy, and he couldn't stop;
The customers, waiting their turns, were all reading
The "Daily," the "Herald," the "Post," little heeding
The young man who blurted out such a blunt question;
Not one raised a head, or even made a suggestion;
And the barber kept on shaving.

"Don't you see, Mr. Brown,"
Cried the youth, with a frown,
"How wrong the whole thing is,
How preposterous each wing is,
How flattened the head is, how jammed down the neck is --
In short, the whole owl, what an ignorant wreck 't is!
I make no apology;
I've learned owl-eology.

I've passed days and nights in a hundred collections,
And cannot be blinded to any deflections
Arising from unskilful fingers that fail
To stuff a bird right, from his beak to his tail.
Mister Brown! Mr. Brown!
Do take that bird down,
Or you'll soon be the laughingstock all over town!"
And the barber kept on shaving.

"I've studied owls,
And other night-fowls,
And I tell you
What I know to be true;
An owl cannot roost
With his limbs so unloosed;
No owl in this world
Ever had his claws curled,
Ever had his legs slanted,
Ever had his bill canted,
Ever had his neck screwed
Into that attitude.
He cant do it, because
'Tis against all bird-laws.

Anatomy teaches,
Ornithology preaches,
An owl has a toe
That can't turn out so!
I've made the white owl my study for years,
And to see such a job almost moves me to tears!
Mr. Brown, I'm amazed
You should be so gone crazed
As to put up a bird
In that posture absurd!
To look at that owl really brings on a dizziness;
The man who stuffed him don't half know his business!"
And the barber kept shaving.

"Examine those eyes
I'm filled with surprise
Taxidermists should pass
Off on you such poor glass;
So unnatural they seem
They'd make Audubon scream,
And John Burroughs laugh
To encounter such chaff.
Do take that bird down;
Have him stuffed again, Brown!"
And the barber kept on shaving!

"With some sawdust and bark
I could stuff in the dark
An owl better than that.
I could make an old hat
Look more like an owl
Than that horrid fowl,
Stuck up there so stiff like a side of coarse leather.
In fact, about him there's not one natural feather."

Just then, with a wink and a sly normal lurch,
The owl, very gravely, got down from his perch,
Walked around, and regarded his fault-finding critic
(Who thought he was stuffed) with a glance analytic,
And then fairly hooted, as if he should say:
"Your learning's at fault this time, anyway:
Don't waste it again on a live bird, I pray.
I'm an owl; you're another. Sir Critic, good day!"
And the barber kept on shaving.

SQL Server Excel Workbench  

Posted by ReelTym

The C.R.U.D. of Excel

Phil and I have teamed up on this workbench, which demonstrates how to
create, read, update and delete information in Excel using T-SQL, from
SQL Server. As always, the workbench is structured so that it can be
pasted into Query Analyser and SSMS, and the individual examples
executed - you can download the .sql from the "Code Download" link above,
load it up and start experimenting!


Creating Excel spreadsheets via ADODB
Manipulating Excel data via a linked server
Synchronising the Spreadsheet with SQL Server Tables
Manipulating Excel data using OPENDATASOURCE and OPENROWSET functions
Creating Excel spreadsheets using sp_MakeWebTask
OLE Automation

We start by showing you how to create an Excel Spreadsheet from
SQL Server in TSQL(Transact SQL), create a worksheet, attach to it as
a linked server, write to it, read from it, update it as if it was an
ordinary SQL Server Database table, and then synchronise the data in
the worksheet with SQL Server. We also illustrate the use of OPENQUERY,

To create the Excel spreadsheet, we show how to attach to an ADODB
source from SQL Server and execute SQL against that source. We then
show you an alternative 'quick cheat' way (using sp_makewebtask) to
create and populate an excel spreadsheet from Transact SQL.

If you need more control over the Excel Spreadsheet that you are
creating, we then show you how to do it via OLE automation. This will
enable you to do anything you can do via keystrokes, and allow you
to generate full Excel reports with pivot tables and Graphs.

Using this technique, you should be able to populate the data, or
place data in particular calls or ranges. You can even do 'macro

A word of caution before you start. If you have your security wide
open, it is not just you who would be able to write out data as
a spreadsheet. An intruder would be able to do it with that list
of passwords or credit-card numbers. In a production system,
this sort of operation needs to be properly ring-fenced. We tend
to create a job queue and have a special user, with the apporpriate
permissions, on the Task Scheduler, to do anything that involves
OLE automation or xp_CMDShell. Security precautions can get quite
complex, but they are outside the scope of the article.

Some of what we illustrate can be done using DTS or SSIS.
Unfortunately, these are outside the scope of this article. In
fact, transferring data between Excel and SQL Server can be done
in a surprising variety of ways and it would be fun one day to
try to list them all

First we need some simple test data
CREATE TABLE ##CambridgePubs
(Pubname VARCHAR(40),
Address VARCHAR(80),
Postcode VARCHAR(8))

INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Bees In The Wall','36 North Road,
Whittlesford, Cambridge','CB2 4NZ'
INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Blackamoors Head','205 Victoria Road,
Cambridge','CB4 3LF'
INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Blue Lion','2 Horningsea Road,
Fen Ditton, Cambridge','CB5 8SZ'
INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Cambridge Blue','85-87 Gwydir Street,
Cambridge','CB1 2LG'
INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Champion Of The Thames','68 King Street,
Cambridge','CB1 1LN'
INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Cross Keys','77 Ermine Street,
Caxton, Cambridge','CB3 8PQ'
INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Crown Inn','11 High Street,
Linton, Cambridge','CB1 6HS'
INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Devonshire Arms','1 Devonshire Road,
Cambridge','CB1 2BH'
INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Duke Of Argyle','90 Argyle Street,
Cambridge','CB1 3LS'
INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Duke Of Wellington','49 Alms Hill,
Bourn, Cambridge','CB3 7SH'
INSERT INTO ##CambridgePubs (PubName, Address, Postcode)
SELECT 'Eagle Public House','Benet Street,
Cambridge','CB2 3QN'
/*And so on. (The full import file is in the ZIP, as is the Excel
Create the table and then execute the contents of CambridgePubs.SQL

Creating Excel spreadsheets via ADODB

First, we need to create the spreadsheet with the correct headings
(PubName, Address, PostCode)

There are two possible ways one might do this. The most obvious way
is using the CREATE statement to create the worksheet and define the
columns, but there seems to be no way of doing this by linking the
excel FILE, unless the Excel file already exists. We need a utility
stored procedure to get at ADODB in order to create databases and
execute DDL and SQL against it. */

@DataSource VARCHAR(100),
@Worksheet VARCHAR(100)=NULL,
@ConnectionString VARCHAR(255)
= 'Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=%DataSource;
Extended Properties=Excel 8.0'
@objExcel INT,
@hr INT,
@command VARCHAR(255),
@strErrorMessage VARCHAR(255),
@objErrorObject INT,
@objConnection INT,
@bucket INT

SELECT @ConnectionString
=REPLACE (@ConnectionString, '%DataSource', @DataSource)
IF @Worksheet IS NOT NULL
SELECT @DDL=REPLACE(@DDL,'%worksheet',@Worksheet)

SELECT @strErrorMessage='Making ADODB connection ',
EXEC @hr=sp_OACreate 'ADODB.Connection', @objconnection OUT
IF @hr=0
SELECT @strErrorMessage='Assigning ConnectionString property "'
+ @ConnectionString + '"',
IF @hr=0 EXEC @hr=sp_OASetProperty @objconnection,
'ConnectionString', @ConnectionString
IF @hr=0 SELECT @strErrorMessage
='Opening Connection to XLS, for file Create or Append'
IF @hr=0 EXEC @hr=sp_OAMethod @objconnection, 'Open'
IF @hr=0 SELECT @strErrorMessage
='Executing DDL "'+@DDL+'"'
IF @hr=0 EXEC @hr=sp_OAMethod @objconnection, 'Execute',
@Bucket out , @DDL
IF @hr<>0
@Source VARCHAR(255),
@Description VARCHAR(255),
@Helpfile VARCHAR(255),

EXECUTE sp_OAGetErrorInfo @objErrorObject, @source output,
@Description output,@Helpfile output,@HelpID output
SELECT @strErrorMessage='Error whilst '
+COALESCE(@strErrorMessage,'doing something')+', '
RAISERROR (@strErrorMessage,16,1)
EXEC @hr=sp_OADestroy @objconnection
/* Now we have it, it is easy */

spExecute_ADODB_SQL @DDL='Create table CambridgePubs
(Pubname Text, Address Text, Postcode Text)',
@DataSource ='C:\CambridgePubs.xls'
--the excel file will have been created on the Database server of the
-- database you currently have a connection to

--We could now insert data into the spreadsheet, if we wanted
spExecute_ADODB_SQL @DDL='insert into CambridgePubs
values (''The Bird in Hand'',
''23, Marshall Road, Cambridge CB4 2DQ'',
''CB4 2DQ'')',
@DataSource ='C:\CambridgePubs.xls'

--you could drop it again!
spExecute_ADODB_SQL @DDL='drop table CambridgePubs',
@DataSource ='c:\CambridgePubs.xls'

/* Manipulating Excel data via a linked server

We can now link to the created excel file as follows */

EXEC sp_addlinkedserver 'CambridgePubDatabase',
@srvproduct = '',
@provider = 'Microsoft.Jet.OLEDB.4.0',
@datasrc = 'C:\CambridgePubs.xls',
@provstr = 'Excel 8.0;'

EXEC sp_addlinkedsrvlogin 'CambridgePubDatabase', 'false'

--to drop the link, we do this!
--EXEC sp_dropserver 'CambridgePubDatabase', 'droplogins'

-- Get the spreadsheet data via OpenQuery
(CambridgePubDatabase, 'select * from [CambridgePubs]')
--or more simply, do this
SELECT * FROM CambridgePubDatabase...CambridgePubs

--so now we can insert our data into the Excel Spreadsheet
INSERT INTO CambridgePubDatabase...CambridgePubs
(Pubname, Address, postcode)
SELECT Pubname, Address, postcode FROM ##CambridgePubs
/*Synchronizing the Spreadsheet with SQL Server tables

As we are directly manipulating the Excel data in the worksheet as if
it was a table we can do joins.

What about synchronising the table after editing the excel spreadsheet?

To try this out, you'll need to delete, alter and insert a few rows
from the excel spreadsheet, remembering to close it after you've done it

--Firstly, we'll delete any rows from ##CambridgePubs
-- that do not exist in the Excel spreadsheet

DELETE FROM ##CambridgePubs
FROM ##CambridgePubs c
LEFT OUTER JOIN CambridgePubDatabase...CambridgePubs ex
ON c.address LIKE ex.address
AND c.pubname LIKE ex.pubname
AND c.postcode LIKE ex.postcode
WHERE ex.pubname IS NULL

-- then we insert into #CambridgePubs any rows in the spreadsheet
-- that don't exist in #CambridgePubs

INSERT INTO ##CambridgePubs (Pubname,Address,Postcode)
SELECT ex.Pubname,ex.Address,ex.Postcode
FROM CambridgePubDatabase...CambridgePubs ex
LEFT OUTER JOIN ##CambridgePubs c
ON c.address LIKE ex.address
AND c.pubname LIKE ex.pubname
AND c.postcode LIKE ex.postcode
WHERE c.pubname IS NULL

--all done (reverse syncronisation would be similar)

/*Manipulating Excel data using OPENDATASOURCE and OPENROWSET

If you don't want to do the linking, you can also read the data like

'Data Source="C:\CambridgePubs.xls";
Extended properties=Excel 8.0')...CambridgePubs
--and write to it

'Data Source="C:\CambridgePubs.xls";
extended Properties=Excel 8.0')...CambridgePubs
SET Address='St. Kilda Road, Cambridge'
WHERE Pubname = 'Jenny Wren'

'Data Source="C:\CambridgePubs.xls";
extended Properties=Excel 8.0')...CambridgePubs
(Pubname,Address,Postcode )
SELECT 'The St George','65 Cavendish Road','CB2 4RT'

--You can read and write toExcel Sheet using OpenRowSet,
--if the mood takes you

'Excel 8.0;DATABASE=C:\CambridgePubs.xls', 'Select * from CambridgePubs')

'Excel 8.0;DATABASE=c:\CambridgePubs.xls',
'Select * from CambridgePubs')
SET Address='34 Glemsford Road' WHERE Address = '65 Cavendish Road'

'Excel 8.0;DATABASE=c:\CambridgePubs.xls',
'Select * from CambridgePubs')
(Pubname, Address, Postcode)
SELECT 'The Bull', 'Antioch Road','CB2 5TY'

/*Creating Excel Spreadsheets using sp_makewebtask

Instead of creating the Excel spreadsheet with OLEDB One can use the

Users must have SELECT permissions to run a specified query and
CREATE PROCEDURE permissions in the database in which the query will run.
The SQL Server account must have permissions to write the generated HTML
document to the specified location. Only members of the sysadmin server
role can impersonate other users.

sp_makewebtask @outputfile = 'c:\CambridgePubsHTML2.xls',
@query = 'Select * from ##CambridgePubs',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Cambridge Pubs',
@dbname ='MyDatabaseName'

/* This is fine for distributing information from databases but no good
if you subsequently want to open it via ODBC.*/

/*OLE Automation

So far, so good. However, we really want rather more than this. When
we create an excel file for a business report, we want the data and we
also want nice formatting, defined ranges, sums, calculated fields
and pretty graphs. If we do financial reporting, we want a pivot table
and so on in order to allow a degree of data mining by the recipient.
A different approach is required.

We can, of course, use Excel to extract the data from the database.
However, in this example, we'll create a spreadsheet, write the data
into it, fit the columns nicely and define a range around the data

*/ ALTER PROCEDURE [dbo].[spDMOExportToExcel] (
@SourceServer VARCHAR(30),
@QueryText VARCHAR(200),
@filename VARCHAR(100),
@WorksheetName VARCHAR(100)='Worksheet',
@RangeName VARCHAR(80)='MyRangeName'
DECLARE @objServer INT,
@objQueryResults INT,
@objCurrentResultSet INT,
@objExcel INT,
@objWorkBooks INT,
@objWorkBook INT,
@objWorkSheet INT,
@objRange INT,
@hr INT,
@Columns INT,
@Rows INT,
@Output INT,
@currentColumn INT,
@currentRow INT,
@ResultSetRow INT,
@off_Column INT,
@off_Row INT,
@command VARCHAR(255),
@ColumnName VARCHAR(255),
@value VARCHAR(255),
@strErrorMessage VARCHAR(255),
@objErrorObject INT,
@Alphabet VARCHAR(27)


IF @QueryText IS NULL
RAISERROR ('A query string is required for spDMOExportToExcel',16,1)

-- Sets the server to the local server
IF @SourceServer IS NULL SELECT @SourceServer = @@servername


SELECT @strErrorMessage = 'instantiating the DMO',
EXEC @hr= sp_OACreate 'SQLDMO.SQLServer', @objServer OUT

--use a trusted connection
IF @hr=0 SELECT @strErrorMessage=
'Setting login to windows authentication on '
+@SourceServer, @objErrorObject=@objServer
IF @hr=0 EXEC @hr=sp_OASetProperty @objServer, 'LoginSecure', 1
IF @hr=0 SELECT @strErrorMessage=
'logging in to the requested server using windows authentication on '
IF @SourceUID IS NULL AND @hr=0 EXEC @hr=sp_OAMethod @objServer,
'Connect', NULL, @SourceServer
EXEC @hr=sp_OAMethod
@objServer, 'Connect', NULL, @SourceServer ,@SourceUID
IF @hr=0
SELECT @strErrorMessage = 'Connecting to '''+@SourceServer+
''' with user ID '''+@SourceUID+'''',
IF @hr=0
EXEC @hr=sp_OAMethod @objServer, 'Connect', NULL,
@SourceServer, @SourceUID, @SourcePWD

--now we execute the query
IF @hr=0 SELECT @strErrorMessage='executing the query "'
+@querytext+'", on '+@SourceServer,
@command = 'ExecuteWithResults("' + @QueryText + '")'
IF @hr=0
EXEC @hr=sp_OAMethod @objServer, @command, @objQueryResults OUT

IF @hr=0
SELECT @strErrorMessage='getting the first result set for "'
+@querytext+'", on '+@SourceServer,
IF @hr=0 EXEC @hr=sp_OAMethod
@objQueryResults, 'CurrentResultSet', @objCurrentResultSet OUT
IF @hr=0
SELECT @strErrorMessage='getting the rows and columns "'
+@querytext+'", on '+@SourceServer
IF @hr=0
EXEC @hr=sp_OAMethod @objQueryResults, 'Columns', @Columns OUT
IF @hr=0
EXEC @hr=sp_OAMethod @objQueryResults, 'Rows', @Rows OUT

--so now we have the queryresults. We start up Excel
IF @hr=0
SELECT @strErrorMessage='Creating the Excel Application, on '
+@SourceServer, @objErrorObject=@objExcel
IF @hr=0
EXEC @hr=sp_OACreate 'Excel.Application', @objExcel OUT
IF @hr=0 SELECT @strErrorMessage='Getting the WorkBooks object '
IF @hr=0
EXEC @hr=sp_OAGetProperty @objExcel, 'WorkBooks',
@objWorkBooks OUT
--create a workbook
IF @hr=0
SELECT @strErrorMessage='Adding a workbook ',
IF @hr=0
EXEC @hr=sp_OAGetProperty @objWorkBooks, 'Add', @objWorkBook OUT

--and a worksheet
IF @hr=0
SELECT @strErrorMessage='Adding a worksheet ',
IF @hr=0
EXEC @hr=sp_OAGetProperty @objWorkBook, 'worksheets.Add',
@objWorkSheet OUT

IF @hr=0
SELECT @strErrorMessage='Naming a worksheet as "'
+@WorksheetName+'"', @objErrorObject=@objWorkBook
IF @hr=0
EXEC @hr=sp_OASetProperty @objWorkSheet, 'name', @WorksheetName

SELECT @currentRow = 1

--so let's write out the column headings
SELECT @currentColumn = 1
WHILE (@currentColumn <= @Columns AND @hr=0)
IF @hr=0
SELECT @strErrorMessage='getting column heading '
+LTRIM(STR(@currentcolumn)) ,
IF @hr=0 EXEC @hr=sp_OAGetProperty @objQueryResults,
@command, @ColumnName OUT
IF @hr=0
SELECT @strErrorMessage='assigning the column heading '+
+ LTRIM(STR(@currentColumn))
+ ' from the query string',
@command='Cells('+LTRIM(STR(@currentRow)) +', '
+ LTRIM(STR(@CurrentColumn))+').value'
IF @hr=0
EXEC @hr=sp_OASetProperty @objExcel, @command, @ColumnName
SELECT @currentColumn = @currentColumn + 1

--format the headings in Bold nicely
IF @hr=0
SELECT @strErrorMessage='formatting the column headings in bold ',
+SUBSTRING(@alphabet,@currentColumn % 26,1)
IF @hr=0 EXEC @hr=sp_OASetProperty @objWorkSheet, @command, 1
--now we write out the data

SELECT @currentRow = 2
WHILE (@currentRow <= @Rows+1 AND @hr=0)
SELECT @currentColumn = 1
WHILE (@currentColumn <= @Columns AND @hr=0)
IF @hr=0
'getting the value from the query string'
+ LTRIM(STR(@currentRow)) +','
+ LTRIM(STR(@currentRow))+')',
IF @hr=0
EXEC @hr=sp_OAMethod @objQueryResults, 'GetColumnString',
@value OUT, @ResultSetRow, @currentColumn
IF @hr=0
SELECT @strErrorMessage=
'assigning the value from the query string'
+ LTRIM(STR(@CurrentRow-1)) +', '
+ LTRIM(STR(@currentcolumn))+')' ,
@command='Cells('+STR(@currentRow) +', '
+ STR(@CurrentColumn)+').value'
IF @hr=0
EXEC @hr=sp_OASetProperty @objExcel, @command, @value
SELECT @currentColumn = @currentColumn + 1
SELECT @currentRow = @currentRow + 1
--define the name range
--Cells(1, 1).Resize(10, 5).Name = "TheData"
IF @hr=0 SELECT @strErrorMessage='assigning a name to a range '
+ LTRIM(STR(@CurrentRow-1)) +', '
+ LTRIM(STR(@currentcolumn-1))+')' ,
@command='Cells(1, 1).Resize('+STR(@currentRow-1) +', '
+ STR(@CurrentColumn-1)+').Name'
IF @hr=0 EXEC @hr=sp_OASetProperty @objExcel, @command, @RangeName

--Now autofilt the columns we've written to
IF @hr=0 SELECT @strErrorMessage='Auto-fit the columns ',
+SUBSTRING(@alphabet,(@Columns / 26),1)
+SUBSTRING(@alphabet,(@Columns % 26),1)+

IF @hr=0 --insert into @bucket(bucket)
EXEC @hr=sp_OAMethod @objWorkSheet, @command, @output out

IF @hr=0 SELECT @command ='del "' + @filename + '"'
IF @hr=0 EXECUTE master..xp_cmdshell @Command, no_output
IF @hr=0
SELECT @strErrorMessage='Saving the workbook as "'+@filename+'"',
@command = 'SaveAs("' + @filename + '")'
IF @hr=0 EXEC @hr=sp_OAMethod @objWorkBook, @command
IF @hr=0 SELECT @strErrorMessage='closing Excel ',
EXEC @hr=sp_OAMethod @objWorkBook, 'Close'
EXEC sp_OAMethod @objExcel, 'Close'

IF @hr<>0
@Source VARCHAR(255),
@Description VARCHAR(255),
@Helpfile VARCHAR(255),

EXECUTE sp_OAGetErrorInfo @objErrorObject,
@source output,@Description output,
@Helpfile output,@HelpID output
SELECT @hr, @source, @Description,@Helpfile,@HelpID output
SELECT @strErrorMessage='Error whilst '
+COALESCE(@strErrorMessage,'doing something')
+', '+COALESCE(@Description,'')
RAISERROR (@strErrorMessage,16,1)
EXEC sp_OADestroy @objServer
EXEC sp_OADestroy @objQueryResults
EXEC sp_OADestroy @objCurrentResultSet
EXEC sp_OADestroy @objExcel
EXEC sp_OADestroy @objWorkBookks
EXEC sp_OADestroy @objWorkBook
EXEC sp_OADestroy @objRange

--Now we can create our pubs spreadsheet, and can do it from any of
--our servers
spDMOExportToExcel @SourceServer='MyServer',
@SourceUID= 'MyUserID',
@SourcePWD = 'MyPassword',
@QueryText = 'use MyDatabase
select Pubname, Address, Postcode from ##CambridgePubs',
@filename = 'C:\MyPubDatabase.xls',
@RangeName ='MyRangeName'

--or if you are using integrated security!
spDMOExportToExcel @SourceServer='MyServer',
@QueryText = 'use MyDatabase
select Pubname, Address, Postcode from ##CambridgePubs',
@filename = 'C:\MyPubDatabase.xls',
@RangeName ='MyRangeName'

/* Although this is a very handy stored procedure, you'll probably need
to modify and add to it for particular purposes.

We use the DMO method because we like to dump build data into Excel
spreadsheets e.g. users, logins, Job Histories. However, an ADODB
version is very simple to do and can be made much faster for reads and

We have just inserted values, but you can insert formulae and formatting
(numberformat) and create or change borders. You can, in fact, manipulate
the spreadsheet in any way you like. When we do this, we record macros in Excel
and then convert these macros to TSQL! Using the above example, it should
be simple*/