MSSQLCity.Com - All about MS SQL
     
About Us  
SSWUG Articles  
Articles  
FAQ  
Administration  
Backup/Restore  
Connectivity  
Development  
General  
Installation  
OLAP  
Replication  
Transfer/move  
Trouble  
SQL 6.5  
Scripts  
Tips  
Test Exams  
Advertise  
Download  
History  
Search  
Traffic  
Related Links  
     
Your button logo
Add to Favorites
 
     
 


How do I run a T-SQL script through SQL-DMO?

Answer:

You can use ExecuteImmediate or CommandShellImmediate methods of SQL-DMO. This is the example to execute T-SQL script from the c:\trig.sql file:

DECLARE @object int
DECLARE @hr int
DECLARE @property varchar(255)
DECLARE @return varchar(255)

EXEC @hr = sp_OACreate 'SQLDMO.SQLServer', @object OUT
IF @hr <> 0
BEGIN
    print 'error create SQLDMO.SQLServer'
    RETURN
END

EXEC @hr = sp_OAMethod
     @object, 'Connect', NULL, 'ServerName', 'Login', 'Password'
IF @hr <> 0
BEGIN
    print 'error with Connect'
    RETURN
END

EXEC @hr = sp_OAMethod @object, 'VerifyConnection', @return OUT
IF @hr <> 0
BEGIN
    PRINT 'error with VerifyConnection'
    RETURN
END

select @property = 'EXEC master..xp_cmdshell "osql -S ServerName ' +
'-U LoginName -P password -i c:\trig.sql"'
EXEC @hr = sp_OAMethod @object, 'ExecuteImmediate', Null , @property
IF @hr <> 0
BEGIN
    print 'error with ExecuteImmediate'
    RETURN
END

-- ahother way to run a T-SQL script
select @property = 'osql -S ServerName -U LoginName -P password -i c:\trig.sql'
EXEC @hr = sp_OAMethod @object, 'CommandShellImmediate', Null , @property
IF @hr <> 0
BEGIN
    print 'error with CommandShellImmediate'
    RETURN
END
Read about the ExecuteImmediate or CommandShellImmediate methods of SQL-DMO in SQL Server Books Online.

See also this link:
Working with COM objects from within T-SQL


 

 
Visit The SQL Server Worldwide User's Group for all the latest news and information about SQL Server, Oracle, DB2 and XML for developers and administrators.

(c) 1997, 2005 Bits on the Wire, Inc