You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

ColdFusion and SQL Server Permission Integration, Part 2

ColdFusion and SQL Server Permission Integration, Part 2

This article is a continuation of the how-to guide (Part 1 ran last month) for setting up a ColdFusion 5 server and a Microsoft SQL Server 7.0 to execute a DTS package through the ColdFusion server.

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.

Let's review the key areas that were covered in Part 1:

  • Description of a DTS package
  • How to configure Windows services for ColdFusion and SQL Server
  • How permissions are passed between servers
  • Useful example code to test ColdFusion permissions and propagation of user rights
  • How to configure SQL Server permissions
  • 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.
    -- [email protected]@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.

    -- 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

    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 +
    SET @Cmd = 'LoadFromSQLServer("' + @Server +'", "", "", 256, "' + @PkgPWD + '", , , "' + @PkgName + '")'

    EXEC @hr = sp_OAMethod @oPKG, @Cmd, NULL
    IF @hr <> 0
    PRINT '*** LoadFromSQLServer failed'
    EXEC sp_displayoaerrorinfo @oPKG , @hr
    RETURN 1

    -- Execute Pkg
    EXEC @hr = sp_OAMethod @oPKG, 'Execute'
    IF @hr <> 0
    PRINT '*** Execute failed'
    EXEC sp_displayoaerrorinfo @oPKG , @hr
    RETURN 1

    -- Check Pkg Errors
    EXEC @ret=spDisplayPkgErrors @oPKG

    -- Unitialize the Pkg
    EXEC @hr = sp_OAMethod @oPKG, 'UnInitialize'
    IF @hr <> 0
    PRINT '*** UnInitialize failed'
    EXEC sp_displayoaerrorinfo @oPKG , @hr
    RETURN 1

    -- Clean Up
    EXEC @hr = sp_OADestroy @oPKG
    IF @hr <> 0
    EXEC sp_displayoaerrorinfo @oPKG , @hr
    RETURN 1

    RETURN @ret

    Stored Procedure 2: spDisplayPKGErrors

    -- display errors from spExecuteDTS execution
    CREATE PROC spDisplayPKGErrors
    @oPkg As integer


    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
    PRINT '*** Unable to get steps'
    EXEC sp_displayoaerrorinfo @oPkg , @hr
    RETURN 1

    EXEC @hr = sp_OAGetProperty @Steps, 'Count', @StepCount OUTPUT
    IF @hr <> 0
    PRINT '*** Unable to get number of steps'
    EXEC sp_displayoaerrorinfo @Steps , @hr
    RETURN 1

    WHILE @StepCount > 0
    EXEC @hr = sp_OAGetProperty @Steps, 'Item', @Step OUTPUT,
    IF @hr <> 0
    PRINT '*** Unable to get step'
    EXEC sp_displayoaerrorinfo @Steps , @hr
    RETURN 1

    EXEC @hr = sp_OAGetProperty @Step, 'ExecutionResult', @StepResult OUTPUT
    IF @hr <> 0
    PRINT '*** Unable to get ExecutionResult'
    EXEC sp_displayoaerrorinfo @Step , @hr
    RETURN 1

    EXEC @hr = sp_OAGetProperty @Step, 'Name', @StepName OUTPUT
    IF @hr <> 0
    PRINT '*** Unable to get step Name'
    EXEC sp_displayoaerrorinfo @Step , @hr
    RETURN 1

    EXEC @hr = sp_OAGetProperty @Step, 'Description', @StepDescription OUTPUT
    IF @hr <> 0
    PRINT '*** Unable to get step Description'
    EXEC sp_displayoaerrorinfo @Step , @hr
    RETURN 1

    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

    SELECT * FROM #PkgResult

    IF @oPkgResult > 0
    PRINT 'Package had ' + CAST(@oPkgResult as varchar) + ' failed step(s)'
    RETURN 9
    PRINT 'Packge Succeeded'
    RETURN 0

    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
    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
    SELECT @output = ' Source: ' + @source
    PRINT @output
    SELECT @output = ' Description: ' + @description
    PRINT @output
    PRINT " sp_OAGetErrorInfo failed."

    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
    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)
    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
    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',


    EXEC spExecuteDTS @Server='YourSQLServer',
    @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

    <CFCATCH TYPE = "Object">
    <CFSET error_message = "The DTS
    Package Object Could Not Be Created.">
    <CFSET r =
    <CFSET error_message = "The DTS Package Could Not Be Loaded From the SQL Server at this time.">
    <CFIF IsDefined("error_message")>
    <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:
    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:


    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

    returnCode = "Yes">

    <cfprocresult name="importData">

    <cfprocparam type="In"
    dbvarname= "@Server"

    <cfprocparam type="In"
    dbvarname= "@PkgName"
    value= "YOUR_DTS_Package_NAME"

    <cfprocparam type="In"

    <!--- <cfprocparam type="In"
    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"




    The return code for the stored procedure was: '#cfstoredproc.statusCode#' <br><br>
    The execution time of the stored procedure, in milliseconds was:


    From the Top Down Troubleshooting

  • Windows Server tasks completed?
    1.  Did you edit the Windows service for ColdFusion?
    (ColdFusion Application Server/ ColdFusion MX Application Server) 2.  Did you edit the Windows service(s) for the SQL Server? (MSSQLServer & SQLServer Agent)
  • SQL Server completed tasks performed under the "SA" account?
    3.  Does your SQL Server database login ID have "db_owner" rights used for the ODBC ColdFusion connection?
    4. Do the extended stored procedures have execute rights for the needed SPROCs in the master database? (Execute rights either have to go to the ID account or to public.)
    A.  sp_OACreate
    B.  sp_OADestroy
    C.  sp_OAMethod
    D.  sp_OASetProperty
    E.  sp_OAGetErrorInfo
    F.  sp_OAGetProperty
  • SQL Server completed tasks performed under the "login ID for the CF ODBC"?
    5.  Create DTS package.
    6.  Did you successfully test your DTS package execution manually?
    7.  Did you create the four needed database SPROCs in your database?
    A.  spExecuteDTS
    B.  spDisplayPKGErrors
    C.  sp_displayoaerrorinfo
    D.  sp_hexadecimal
    8.  Did you test the SQL Server Enterprise Manager SPROC execution successfully?
  • ColdFusion Server completed tasks?
    9.  Test the ColdFusion CFOBJECT COM method for execution?
    10.  Test the ColdFusion CFSTOREDPROC method for execution?

    Still Having Problems?
    Unfortunately even if you follow this guide step by step there are no guarantees for success! You may still have problems getting your DTS packages to execute properly from COM, SPROCs, or just from manually executing your DTS package in general. In most cases your issues will have to do with permissions someplace in your system. For others using COM, you may need to update your Windows OS with the latest patches and version of Internet Explorer on the ColdFusion server. However, in the end, the information contained here should provide you with enough information on where to begin looking for your problem areas and the order to follow. Good troubleshooting skills and a step-bystep testing approach are the best ways to resolve any issues.

  • Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    IoT & Smart Cities Stories
    We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
    Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
    René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
    With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
    Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
    Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
    Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science" is responsible for guiding the technology strategy within Hitachi Vantara for IoT and Analytics. Bill brings a balanced business-technology approach that focuses on business outcomes to drive data, analytics and technology decisions that underpin an organization's digital transformation strategy.
    DXWorldEXPO LLC, the producer of the world's most influential technology conferences and trade shows has announced the 22nd International CloudEXPO | DXWorldEXPO "Early Bird Registration" is now open. Register for Full Conference "Gold Pass" ▸ Here (Expo Hall ▸ Here)