Oct. 15, 2003 12:00 AM
The main objective of the guide is to create a DTS package that will result in file output that will be delivered to a network UNC path or mapped drive using a set of stored procedures executed by ColdFusion. The configuration for this setup will also allow a ColdFusion server to properly propagate user rights across networked servers and domains for using shared access.
Although this guide focuses on the use of a ColdFusion 5 server and SQL Server 7.0, you can easily apply this information to a ColdFusion MX server and SQL Server 2000.
How to create and execute a simple DTS package in the SQL Server Enterprise Manager
How to Install and Create the Stored Procedures in SQL Server for ColdFusion OLE Automation Execution
Complete this section logged onto the SQL Server using your ColdFusion ODBC login account.
The information below is based on Dan G. Switzer's Pengoworks Web site. The origin of the code is actually based on the Microsoft Online Books for SQL Server. It provides information on running a DTS package through a stored procedure using OLE automation.
The Microsoft SQL Server Books Online is a great reference and you can easily look up any of the information contained below. Don't look in your Enterprise Manager window for it though. This information is typically located in Start>Programs> Microsoft SQL Server 7.0> Books Online, and is optional when SQL Server installs, but if you did a typical install you should already have this handy information. Two great Web sites to check for more information on this are www.pengoworks.com/index.cfm?action=articles:spExecuteDTS ("Executing a DTS Package from CF/ASP/PHP/SQL"); and www.databasejournal.com/features/mssql/article.php/1459181 ("Data Transformation Services").

To Start:
1. You will need to create four stored procedures in your database (spDisplayPKGErrors, spExecuteDTS, sp_displayoaerrorinfo, and sp_hexadecimal). Place these stored procedures, aka SPROCs, in the desired database(s) in which you wish to execute your DTS packages from ColdFusion. These all have to be created under the same user account that you use for your ODBC connection. So if ACCOUNT1 is your ODBC user name, you must log into your SQL Server Enterprise manager with that ID when you set these SPROCs up.
2. Start by opening your database in the Enterprise Manager, right-click on "Stored Procedures", and click on "New Stored Procedure."
3. Once the new SPROC window is opened, remove the code highlighted below (CREATE PROCEDURE [PROCEDURE NAME] AS) and paste in one of the SPROCs below. Click APPLY and OK and repeat this process for the other stored procedures all listed below.
Stored Procedure 1: spExecuteDTS
This is the main SPROC used for OLE automation. I went through and commented the code, so you'll know what's going on in the SPROC if you're interested in reading it.
-- Local variable(s) use: @
-- Global variable(s) use: @@
-- Note: There are over 30 global variables a.k.a. parameterless system functions available for use.
-- E.g.@@VERSION returns the current version of your SQL Server.
-- Creating the stored procedure a.k.a. Sproc
-- Code usage below
-- CREATE PROEDURE|PROC <sproc name>
-- @parameter_name data_type> [= default|NULL] [VARYING] [OUTPUT]
-- Note: By adding [= NULL] or a value to a parameter it becomes an optional variable from the user executing the procedure.
CREATE PROC spExecuteDTS
@Server varchar(255), -- Required: SQL Server name
@PkgName varchar(255), -- Required: Package Name
(Defaults to most recent version)
@ServerPWD varchar(255) = Null, -- Optional: Server Password if
using SQL Security to load Package (UID is SUSER_NAME())
@IntSecurity bit = 0, -- Optional: 0 = SQL
Server Security, 1 = Integrated Security
@PkgPWD varchar(255) = '' -- Optional: Package Password
-- Below the AS statement is the code for the procedure.
AS
-- The SET statement is usually used for setting variables in the fashion you see in most procedural languages.
-- Code Usage e.g. SET @Age = 21
SET NOCOUNT ON
/*
Return Values
- 0 Successful execution of Package
- 1 OLE Error
- 9 Failure of Package
*/
-- The DECLARE statement declares variable(s). Note: The default value for the variable is always NULL.
-- Code Usage e.g. DECLARE @<variable name> <variable type>
DECLARE @hr int, @ret int, @oPKG int, @Cmd varchar(1000)
-- The EXEC|EXECUTE keyword is required since a call to a sproc wasn't the first thing in the batch.
-- OUTPUT Parameter: Will return a value to the sproc.
-- Question: How do you run a DTS package from the Query Analyzer or stored procedure?
-- Answer: By using OLE Automation objects such as sp_OACreate, sp_OAGetProperty, sp_OAMethod
-- Create a Pkg Object
/* The main procedure, sp_displayoaerrorinfo, takes the return code from any of the standard OLE Automation stored procedures, and displays the error Source and Description using sp_OAGetErrorInfo. It also calls sp_hexadecimal to convert the integer error code into a string (char) representation of the true hexadecimal value. */
EXEC @hr = sp_OACreate 'DTS.Package', @oPKG OUTPUT
IF @hr <> 0 -- If variable
NOT EQUAL to ZERO continue.
BEGIN -- Grouping the
code into code blocks BEGINS here.
PRINT '*** Create Package object failed'
EXEC sp_displayoaerrorinfo @oPKG, @hr
RETURN 1
-- RETURN Values: Used to determine the execution of the sproc. FYI: 1 equals an OLE Error
END -- Grouping the code into
code blocks ENDS here.
-- Evaluate Security and Build LoadFromSQLServer Statement
/* Syntax: Package.LoadFromSQLServer ServerName, [ServerUserName],
[ServerPassword], [Flags],
[PackagePassword], [PackageGuid],
[PackageVersionGuid], [PackageName], [pVarPersistStgOfHost] */
-- ServerName = Server name.
-- ServerUserName = Server user name.
-- ServerPassword = Server user password.
-- Flags = Value from the DTSSQLServerStorageFlags constants indicating user authentication type.
-- PackagePassword = Package password if the package is encrypted.
-- PackageGuid = Package identifier, which is a string representation of a globally unique identifier (GUID).
-- PackageVersionGuid = Version identifier which is a string representation of a GUID.
-- PackageName = Package name.
-- pVarPersistStgOfHost = Screen layout information associated with a package (for internal use only).
-- Syntax: SUSER_SNAME()
/* This is the user security identification number. server_user_sid, which is optional, is varbinary(85). server_user_sid can be the security identification number of any Microsoft SQL Server login or Microsoft Windows NT user or group. If server_user_sid is not specified, information about the current user is returned. */
-- sp_OAMethod Calls a method of an OLE object.
-- Syntax:
-- sp_OAMethod objecttoken, methodname [ , returnvalue OUTPUT ] [ , [ @parametername = ] parameter [ OUTPUT ] [ ...n ] ]
IF @IntSecurity = 0
SET @Cmd = 'LoadFromSQLServer("' + @Server +'", "' + SUSER_SNAME()
+ '", "' + @ServerPWD + '", 0, "' + @PkgPWD + '", , , "' + @PkgName +
'")'
ELSE
SET @Cmd = 'LoadFromSQLServer("' + @Server +'", "", "", 256, "' + @PkgPWD + '", , , "' + @PkgName + '")'
EXEC @hr = sp_OAMethod @oPKG, @Cmd, NULL
IF @hr <> 0
BEGIN
PRINT '*** LoadFromSQLServer failed'
EXEC sp_displayoaerrorinfo @oPKG , @hr
RETURN 1
END
-- Execute Pkg
EXEC @hr = sp_OAMethod @oPKG, 'Execute'
IF @hr <> 0
BEGIN
PRINT '*** Execute failed'
EXEC sp_displayoaerrorinfo @oPKG , @hr
RETURN 1
END
-- Check Pkg Errors
EXEC @ret=spDisplayPkgErrors @oPKG
-- Unitialize the Pkg
EXEC @hr = sp_OAMethod @oPKG, 'UnInitialize'
IF @hr <> 0
BEGIN
PRINT '*** UnInitialize failed'
EXEC sp_displayoaerrorinfo @oPKG , @hr
RETURN 1
END
-- Clean Up
EXEC @hr = sp_OADestroy @oPKG
IF @hr <> 0
BEGIN
EXEC sp_displayoaerrorinfo @oPKG , @hr
RETURN 1
END
RETURN @ret
Stored Procedure 2: spDisplayPKGErrors
-- display errors from spExecuteDTS execution
CREATE PROC spDisplayPKGErrors
@oPkg As integer
AS
SET NOCOUNT ON
DECLARE @StepCount int
DECLARE @Steps int
DECLARE @Step int
DECLARE @StepResult int
DECLARE @oPkgResult int
DECLARE @hr int
DECLARE @StepName varchar(255)
DECLARE @StepDescription varchar(255)
IF OBJECT_ID('tempdb..#PkgResult') IS NOT NULL
DROP TABLE #PkgResult
CREATE TABLE #PkgResult
(
StepName varchar(255) NOT NULL,
StepDescription varchar(255) NOT NULL,
Result bit NOT NULL
)
SELECT @oPkgResult = 0
EXEC @hr = sp_OAGetProperty @oPkg, 'Steps', @Steps OUTPUT
IF @hr <> 0
BEGIN
PRINT '*** Unable to get steps'
EXEC sp_displayoaerrorinfo @oPkg , @hr
RETURN 1
END
EXEC @hr = sp_OAGetProperty @Steps, 'Count', @StepCount OUTPUT
IF @hr <> 0
BEGIN
PRINT '*** Unable to get number of steps'
EXEC sp_displayoaerrorinfo @Steps , @hr
RETURN 1
END
WHILE @StepCount > 0
BEGIN
EXEC @hr = sp_OAGetProperty @Steps, 'Item', @Step OUTPUT,
@StepCount
IF @hr <> 0
BEGIN
PRINT '*** Unable to get step'
EXEC sp_displayoaerrorinfo @Steps , @hr
RETURN 1
END
EXEC @hr = sp_OAGetProperty @Step, 'ExecutionResult', @StepResult OUTPUT
IF @hr <> 0
BEGIN
PRINT '*** Unable to get ExecutionResult'
EXEC sp_displayoaerrorinfo @Step , @hr
RETURN 1
END
EXEC @hr = sp_OAGetProperty @Step, 'Name', @StepName OUTPUT
IF @hr <> 0
BEGIN
PRINT '*** Unable to get step Name'
EXEC sp_displayoaerrorinfo @Step , @hr
RETURN 1
END
EXEC @hr = sp_OAGetProperty @Step, 'Description', @StepDescription OUTPUT
IF @hr <> 0
BEGIN
PRINT '*** Unable to get step Description'
EXEC sp_displayoaerrorinfo @Step , @hr
RETURN 1
END
INSERT #PkgResult VALUES(@StepName, @StepDescription, @StepResult)
PRINT 'Step ' + @StepName + ' (' + @StepDescription + ') ' + CASE
WHEN @StepResult = 0 THEN 'Succeeded' ELSE 'Failed' END
SELECT @StepCount = @StepCount - 1
SELECT @oPkgResult = @oPkgResult + @StepResult
END
SELECT * FROM #PkgResult
IF @oPkgResult > 0
BEGIN
PRINT 'Package had ' + CAST(@oPkgResult as varchar) + ' failed step(s)'
RETURN 9
END
ELSE
BEGIN
PRINT 'Packge Succeeded'
RETURN 0
END
Stored Procedure 3: sp_displayoaerrorinfo
This information is directly from the MS Online Book. You can use the following sp_displayoaerrorinfo stored procedure to display OLE Automation error information when one of the OLE Automation procedures returns a nonzero HRESULT return code. This sample stored procedure also uses sp_hexadecimal.
CREATE PROCEDURE sp_displayoaerrorinfo
@object int,
@hresult int
AS
DECLARE @output varchar(255)
DECLARE @hrhex char(10)
DECLARE @hr int
DECLARE @source varchar(255)
DECLARE @description varchar(255)
PRINT 'OLE Automation Error Information'
EXEC sp_hexadecimal @hresult, @hrhex OUT
SELECT @output = ' HRESULT: ' + @hrhex
PRINT @output
EXEC @hr = sp_OAGetErrorInfo @object, @source OUT, @description OUT
IF @hr = 0
BEGIN
SELECT @output = ' Source: ' + @source
PRINT @output
SELECT @output = ' Description: ' + @description
PRINT @output
END
ELSE
BEGIN
PRINT " sp_OAGetErrorInfo failed."
RETURN
END
Stored Procedure 4: sp_hexadecimal
This information is also directly from the MS Online Book.
CREATE PROCEDURE sp_hexadecimal
@binvalue varbinary(255),
@hexvalue varchar(255) OUTPUT
AS
DECLARE @charvalue varchar(255)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH(@binvalue)
SELECT @hexstring = '0123456789abcdef'
WHILE (@i <= @length)
BEGIN
DECLARE @tempint int
DECLARE @firstint int
DECLARE @secondint int
SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
SELECT @firstint = FLOOR(@tempint/16)
SELECT @secondint = @tempint - (@firstint*16)
SELECT @charvalue = @charvalue +
SUBSTRING(@hexstring, @firstint+1, 1) +
SUBSTRING(@hexstring, @secondint+1, 1)
SELECT @i = @i + 1
END
SELECT @hexvalue = @charvalue
Your configuration is now complete.
How to Test Configurations in SQL Server
Complete this section logged onto the SQL Server using your same ColdFusion ODBC login account.
Open your SQL Server Enterprise Manager and click on Tools>SQL Server Query Analyzer. You'll need to test and execute the DTS package here, so you'll see any errors that may occur in the results window. This is where you'll go to help troubleshoot a failing DTS package.
If you're using SQL Server Security Authorization, which is what you are using if you're logged in with the ODBC user's ID, you can use one of the following two commands to execute the SPROC, which will execute the DTS package:
EXEC spExecuteDTS @Server='YourSQLServer', @PkgName='DTS_xxx',
@ServerPWD='YourLogInPassword'
or
EXEC spExecuteDTS @Server='YourSQLServer',
@PkgName='DTS_xxx',
@ServerPWD='YourLogInPassword', @IntSecurity = 0
If you're using SQL Server Integrated Security Authorization, you can use the following command to execute the SPROC, which will also execute the DTS package. (This would mean you're logged in to the Enterprise Manager with your Windows login account.)
EXEC spExecuteDTS @Server='YourSQLServer',
@PkgName='DTS_xxx', @IntSecurity = 1
Your testing is complete!
Okay, so you're getting anxious to see these new methods work aren't you? Before we try our new SPROC method, let's first test the DTS package execution an easier way by executing it through a COM Object. You probably are wondering why I'm pushing the SPROC method over COM. For starters, MX seems to have some COM issues that I'm not sure have been resolved yet. So when we decide to migrate to MX, I want all my code to work. There are also some security concerns when using COM. And finally, the most important reason to use a SPROC over COM – speed! There is a performance gain from executing your packages through a SPROC that uses OLE automation over using the COM object to execute the package. Cut and paste the code below into a template and execute it. Example for DTS Execution via a COM Object
<CFTRY>
<CFOBJECT TYPE="COM" NAME="objDTS"
CLASS="DTS.Package" ACTION="CREATE">
<CFCATCH TYPE = "Object">
<CFSET error_message = "The DTS
Package Object Could Not Be Created.">
</CFCATCH>
</CFTRY>
<CFTRY>
<CFSET r =
objDTS.LoadfromSQLServer("YOUR_SQL_SERVER_NAME
","YOUR_ODBC_USER_NAME"," YOUR_ODBC_PASSWORD",
0,"","","","YOUR_DTS_Package_NAME","")>
<CFCATCH>
<CFSET error_message = "The DTS Package Could Not Be Loaded From the SQL Server at this time.">
</CFCATCH>
</CFTRY>
<CFIF IsDefined("error_message")>
<CFOUTPUT>#error_message#</CFOUTPUT>
</CFIF>
<CFSET p = objDTS.Execute()>
There are two examples, first calling it via COM (via CFOBJECT) and then via a stored procedure (using CFPROCPARAM). You will need to change the four options listed below:
A. YOUR_SQL_SERVER_NAME
B. YOUR_ODBC_USER_NAME
C. YOUR_ODBC_PASSWORD
D. YOUR_DTS_Package_NAME
If you're wondering what the options are for the objDTS.LoadfromSQLServer that you can use, they are listed below with a full example of the available options:
ObjectName.LoadFromSQLServer("ServerName",
"ServerUserName",
"ServerPassword",
"Flags",
"PackagePassword",
"PackageGuid",
"PackageVersionGuid",
"PackageName",
"pVarPersistStgOfHost")
Now here's what you've been waiting for, the code to call a SPROC, which will execute your DTS package from ColdFusion.
Example for DTS Execution via a SPROC
<CFSTOREDPROC PROCEDURE="spExecuteDTS"
DATASOURCE="YOUR_ODBC_USER_NAME"
debug="Yes"
returnCode = "Yes">
<cfprocresult name="importData">
<cfprocparam type="In"
cfsqltype="CF_SQL_VARCHAR"
dbvarname= "@Server"
value= "YOUR_SQL_SERVER_NAME"
null="no">
<cfprocparam type="In"
cfsqltype="CF_SQL_VARCHAR"
dbvarname= "@PkgName"
value= "YOUR_DTS_Package_NAME"
null="NO">
<cfprocparam type="In"
cfsqltype="CF_SQL_VARCHAR"
dbvarname="@ServerUserID"
value="YOUR_ODBC_USER_NAME"
null="NO">
<!--- <cfprocparam type="In"
cfsqltype="CF_SQL_VARCHAR"
dbvarname="@ServerPWD"
value="YOUR_ODBC_PASSWORD"
null="NO"> --->
<!--- Note: If you run this with a local SA account or you're using the SQL Server Integrated Security you'll need the line below. If your code doesn't work, comment out the line below. --->
<cfprocparam type="In"
cfsqltype="CF_SQL_VARCHAR"
dbvarname="@IntSecurity"
value="1"
null="NO">
</CFSTOREDPROC>
<hr>
<cfoutput>
The return code for the stored procedure was: '#cfstoredproc.statusCode#' <br><br>
The execution time of the stored procedure, in milliseconds was:
#cfstoredproc.ExecutionTime#.
</cfoutput>
From the Top Down Troubleshooting