blog community

Welcome to blog community Sign in | Join | Help
in Search

Bertrand Rohrbock

All things related to SQL Server administration

Object references and SQL

While it might seem strange or even impossible to work with objects in SQL it is possible. I stumbled upon this recently while I was investigating a way to automatically drop and recreate indexes on a SQL 2000 server.

DECLARE @object INT
EXEC sp_OACreate 'SQLDMO.SQLServer', @object OUT
EXEC sp_OASetProperty @object, 'LoginSecure', TRUE

With this statement an object is created and the reference to it is stored as an integer in @object. We also set the LoginSecure property to true. We can get and set properties and call methods of the object with the sp_OA..... functions

SET @CmdStr = 'Connect('+@@SERVERNAME+')'
EXEC sp_OAMethod @object,@CmdStr

With this statement the Connect function on the object is called with the servername of the server you're running the script on as the parameter. After connecting it's possible to approach objects on the SQL server, this might not seem very usefull yet as SQL is the language to approach objects on a database server. However it is usefull in getting object definitions.

SET @CmdStr = 'Databases("testdatabase").Tables("table1").Indexes("index1").Script(5)'
EXEC sp_OAMethod @object, @CmdStr

Now it gets a little more interesting, we approach the object named index1 in the collection indexes in the collection of tables in the collection of databases and call the Script() method on it. The number 5 is a bitpattern that indicates the objects and the deletion of the object if it exists need to be scripted.

I wish I had some more time to dig into this, I am sure there are more gems to be found in this mechanism. 

Published Tuesday, September 25, 2007 2:04 PM by BertrandR

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

Christian Hageraats said:

Dear Bertrand, It would be nice if you declare the @CmdStr variable. Plus if you are using a different schema then dbo you can place the schema name with the table name. Tables(".table1").Indexes("index1").Script(5)' With best regards, Christian Hageraats
May 26, 2008 5:10 PM

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server, by Telligent Systems