Accessing WinCC 6.0 SP2 Tag Logging Database via OLE DB

David Krause13 min read
SiemensTutorial / How-toWinCC
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

Accessing WinCC 6.0 SP2 Tag Logging Database via OLE DB

SIMATIC WinCC V6.0 SP2 and V6.2 SP2 store all process, alarm, and tag logging values in Microsoft SQL Server databases. Field engineers frequently need to read historical tag values from an HMI I/O field in response to a user-entered date. This article documents the official Siemens path to do that: enabling the WinCC OLE DB Provider, registering the CC_SP_ReadTags stored procedure via the Connectivity Pack, and triggering the query from a WinCC button using VBScript or a C script. The article also covers the V6.2 SP2 delivery release notes, the SQL Server Import/Export wizard integration, and a documented security weakness that must be remediated before exposing the database to the plant network.

Note. WinCC V6.0 SP2 and V6.2 SP2 are legacy releases. The Connectivity Pack license, the WinCC OLE DB Provider, and the CC_SP_ReadTags stored procedure are still the canonical way to query runtime archives in those versions. Procedures here are also a useful baseline when migrating older projects to WinCC V7.x or TIA Portal WinCC Professional, where the stored-procedure interface has been expanded.

1. WinCC V6.0/V6.2 SP2 Tag Logging Architecture

Tag Logging in WinCC is a server-side subsystem that periodically samples internal tags, external process tags, and derived tags and writes them to a set of segmented SQL Server databases. Each Tag Logging archive consists of:

  • An archive configuration in the WinCC Explorer (Data -> Tag Logging).
  • One or more segmented runtime databases stored under \Siemens\WinCC\WinCCProjects\<project>\ArchiveManager\TagLogging\.
  • MS SQL Server 2000 (V6.0) or MS SQL Server 2005 (V6.2) instance running the runtime.

The default segments are TLG_R_<archive>_<segment>_<timestamp>.mdf. Without additional licensing, the runtime database is opaque to external applications: the tables cannot be opened in SQL Server Management Studio and queries are rejected by the WinCC archive manager.

Table 1 - WinCC V6.x Tag Logging database access methods
Method License Required Read Write Recommended Use
WinCC Online Trend Control / Online Table Control WinCC RT basic Yes No Operator visualization in WinCC pictures
WinCC OLE DB Provider (direct OLE DB / ADO) Connectivity Pack Yes Limited External applications, C#/VB clients, custom reports
CC_SP_ReadTags stored procedure Connectivity Pack Yes No Time-range queries with aggregation
SQL Server Import/Export Wizard (OLE DB) Connectivity Pack Yes No Bulk extract, ETL, reporting
OPC Historical Access (HDA) Server Connectivity Pack / OPC HDA Yes No OPC HDA clients (cross-vendor)

2. Prerequisites and Licensing

Before you can read runtime tag values from outside the WinCC picture, the following prerequisites must be met on the WinCC server (and on any client machine that will host the WinCC OLE DB Provider):

  1. Microsoft SQL Server 2000 SP4 (WinCC V6.0 SP2) or SQL Server 2005 SP2/SP3 (WinCC V6.2 SP2) installed and running. Verify the SQLSERVERAGENT and MSSQLSERVER services are started.
  2. WinCC V6.0 SP2 or V6.2 SP2 runtime installed. The SIMATIC WinCC V6.2 SP2 Delivery Release (ID 26636449) lists the precise build and the OLE DB Provider components delivered with the media.
  3. WinCC Connectivity Pack license activated on the runtime computer. Without this license the OLE DB Provider still installs but returns 0x80040E1D on any open call.
  4. WinCC Archive Server license if you intend to query the Central Archive Server (CAS) rather than a local project. CAS is included in the V6.2 SP2 delivery release.
  5. Read access to the WinCC project directory and the SQL Server sysadmin role for the user account that runs the query (for one-time configuration only; runtime queries can use a least-privilege account).
Security. CVE-2014-4685 affects "SIMATIC WinCC before 7.3" and allows local users to gain privileges by leveraging weak system-object access control. See the NVD record for CVE-2014-4685. Do not run WinCC runtime on a workstation shared with untrusted local accounts; restrict local-group membership on the WinCC server and apply the latest WinCC V7.3+ hotfix or migrate to a current TIA Portal WinCC Professional installation.

3. Enabling the WinCC OLE DB Provider

The WinCC OLE DB Provider is the COM provider WinCCOLEDBProvider.1. It is registered automatically by the Connectivity Pack installer. To confirm it is present:

  1. Open a command prompt and run regedit.exe.
  2. Navigate to HKEY_CLASSES_ROOT\WinCCOLEDBProvider.1. The default value should read Siemens WinCC OLE DB Provider.
  3. Open HKEY_CLASSES_ROOT\CLSID and confirm the GUID {5798D85C-1C36-4694-9E2B-1D71D8B72E14} (V6.2 SP2) is registered under InProcServer32 pointing to WinCCOLEDBProvider.dll.

The connection string used by external applications is:

Provider=WinCCOLEDBProvider.1;Catalog=CC_<ProjectName>_<YY-MM-DD>_<HH-MM-SS>_<ms>;Data Source=.\WinCC

The catalog name follows the pattern CC_<Project>_<RuntimeStart>. You can read the active catalog name from the WinCC Archive Manager status window or by enumerating master.dbo.sysdatabases in SQL Server.

Table 2 - WinCC OLE DB connection string parameters
Parameter Required Value / Example Description
Provider Yes WinCCOLEDBProvider.1 COM ProgID of the WinCC OLE DB Provider
Catalog Yes CC_Project_13-11-25_06-00-00_000 Active runtime archive catalog
Data Source Yes .\WinCC or Server\WinCC SQL Server instance hosting the WinCC databases
User ID / Password Optional SQL account Only required for remote SQL authentication; integrated Windows auth is default
Mode Optional Read (default) / Write Read-only is enforced by the archive manager

4. The CC_SP_ReadTags Stored Procedure

When the Connectivity Pack is installed, the WinCC installer registers a set of system stored procedures in the active runtime catalog. The most useful for date-based HMI queries is CC_SP_ReadTags, defined in the master database and accessible from any WinCC runtime catalog.

4.1 Stored procedure signature

CC_SP_ReadTags
  @sTagname   nvarchar(255),     -- Tag name as configured in WinCC Tag Logging
  @dtFrom     datetime,          -- Start of the time window
  @dtTo       datetime,          -- End of the time window
  @sFilter    nvarchar(4000) = NULL,  -- Optional WHERE clause
  @sOrder     nvarchar(255)  = N'Timestamp ASC',
  @sParams    nvarchar(4000) = NULL   -- Aggregation / TIMESTEP / MAXROWS

4.2 Practical example

The following invocation returns the value of tag Boiler_Pressure between 2013-11-25 06:00:00 and 2013-11-26 07:59:59, resampled at 60-second intervals with a 2-second tolerance for missing values:

EXEC CC_SP_ReadTags
    N'Boiler_Pressure',
    '2013-11-25 06:00:00',
    '2013-11-26 07:59:59',
    NULL,
    N'Timestamp ASC',
    N'TIMESTEP=60,2'
Table 3 - CC_SP_ReadTags TIMESTEP and aggregation parameters
Parameter Format Effect
TIMESTEP=n[,tol] Integer seconds, optional tolerance seconds Resample archive values to a uniform interval
AGGREGATION=AVG AVG / MIN / MAX / SUM / COUNT Apply aggregate over each resampled bucket
MAXROWS=n Integer Cap result set size (default 10 000)
LIMIT=n Integer Return the first n rows only

5. SQL Server Import/Export Wizard Integration

The WinCC V6.2 SP2 delivery release notes (ID 26636449) describe the WinCC OLE DB Provider as a registered source for the Microsoft SQL Server Import/Export Wizard. The wizard becomes available on the SQL Server Management Studio toolbar after the Connectivity Pack is installed. The provider enables bulk extract of Tag Logging, Alarm Logging, and user archive data without writing custom OLE DB code.

  1. Start the SQL Server Import/Export Wizard from the SQL Server 2005 instance that hosts the WinCC runtime.
  2. Choose a destination (e.g., flat file, another SQL Server, Oracle, ODBC).
  3. In Choose a Data Source, set Provider = Microsoft OLE DB Driver for SQL Server and enter the WinCC connection string, or select .NET Framework Data Provider for OLE DB with the WinCC OLE DB connection string from Section 3.
  4. Select the dbo.TLG (Tag Logging) or dbo.ATL (Alarm Logging) tables, or pass a SELECT statement that calls CC_SP_ReadTags.
  5. Run the package immediately or save as SSIS package. The wizard writes directly to the destination; it does not lock the runtime archive.
Field tip. If the wizard does not list the WinCC provider, reinstall the Connectivity Pack on the SQL Server machine (not just the WinCC server) and re-register WinCCOLEDBProvider.dll with regsvr32.exe.

6. HMI Implementation: Date Input -> Query -> Output

The original requirement is a WinCC picture with one I/O field for date entry, a button to trigger the search, and one I/O field to display the value. The standard pattern is a VBScript action on the button that opens an ADO connection, executes CC_SP_ReadTags, and writes the result to an internal tag bound to the output I/O field.

6.1 Configure internal tags

Add the following internal tags in WinCC Explorer under Internal Tags:

Table 4 - Internal tags for the date-query picture
Tag Name Data Type Purpose
Query_SearchDate Text tag, 16 chars Holds the user-entered date (DD.MM.YYYY)
Query_ResultValue Float / Signed 32-bit Bound to the output I/O field
Query_ResultTime Text tag, 32 chars Timestamp of the returned value
Query_Status Unsigned 16-bit 0 = OK, 1 = no data, 2 = error

6.2 I/O field and button configuration

  1. Insert an I/O field on the picture, set Tag = Query_SearchDate, format = String, output/input = Input. Configure the field update on Change to write back the string.
  2. Insert a second I/O field, set Tag = Query_ResultValue, output = Output only, format 9.999.
  3. Insert a button, Event -> Mouse -> Press left: VBS Action (see script below).

6.3 VBScript action for the button

Option Explicit

' --- Configuration ---
Const TAG_NAME   = "Boiler_Pressure"
Const WINCC_PROJ = "MyPlant"
Const SQL_INSTANCE = ".\WinCC"

Dim sConn, sCatalog, dtFrom, dtTo, sResult
Dim oConn, oRS, iRC

' Determine the active runtime catalog by enumerating the WinCC databases
sConn = "Provider=WinCCOLEDBProvider.1;Data Source=" & SQL_INSTANCE & ";"
Set oConn = CreateObject("ADODB.Connection")
oConn.ConnectionString = sConn
oConn.CursorLocation   = 3   ' adUseClient
oConn.Open

Set oRS = CreateObject("ADODB.Recordset")
oRS.ActiveConnection = oConn
oRS.Source = "SELECT Catalog FROM dbo.CC_Configuration"
oRS.Open
If Not oRS.EOF Then sCatalog = oRS.Fields(0).Value

' Build a 24-hour window from the entered date (00:00:00 to 23:59:59)
dtFrom = CDate(SmartTags("Query_SearchDate").Value & " 00:00:00")
dtTo   = DateAdd("s", 86399, dtFrom)

' Build the EXEC call
sResult = "EXEC CC_SP_ReadTags '" & TAG_NAME & "','" & _
          FormatDateTime(dtFrom, vbGeneralDate) & "','" & _
          FormatDateTime(dtTo,   vbGeneralDate) & "',NULL,'Timestamp ASC','TIMESTEP=60,2'"

On Error Resume Next
oRS.Source = sResult
oRS.Open
iRC = Err.Number
If iRC <> 0 Then
    SmartTags("Query_Status").Value = 2
    SmartTags("Query_ResultValue").Value = 0
ElseIf oRS.EOF Then
    SmartTags("Query_Status").Value = 1
    SmartTags("Query_ResultValue").Value = 0
Else
    SmartTags("Query_ResultValue").Value = CDbl(oRS.Fields("RealValue").Value)
    SmartTags("Query_ResultTime").Value  = CStr(oRS.Fields("Timestamp").Value)
    SmartTags("Query_Status").Value     = 0
End If
On Error Goto 0

oRS.Close : oConn.Close
Set oRS = Nothing : Set oConn = Nothing

The script uses the configuration view dbo.CC_Configuration to discover the active catalog at runtime, so the picture does not need to be re-engineered when the runtime database rotates. If you prefer a hard-coded catalog, replace the SELECT block with the literal string documented in the project.

7. C-Script Equivalent (Optional)

Engineers maintaining older WinCC V6.x pictures that already use C actions can implement the same query with the SQL functions exposed by the ap_sql.h interface:

#include "apdefap.h"

void OnClick(char* lpszPictureName, char* lpszObjectName, char* lpszPropertyName)
{
    char szCatalog[128], szConn[256];
    long lRet;
    SQL_DATE_STRUCT stFrom, stTo;

    /* Build connection string */
    sprintf(szConn,
            "Provider=WinCCOLEDBProvider.1;Catalog=CC_MyPlant_13-11-25_06-00-00_000;"
            "Data Source=.\\WinCC");

    /* Convert internal tag value to SQL_DATE_STRUCT */
    /* ... (read Query_SearchDate, parse DD.MM.YYYY, fill stFrom) ... */
    stTo.year = stFrom.year; stTo.month = stFrom.month; stTo.day = stFrom.day;
    stTo.hour = 23; stTo.minute = 59; stTo.second = 59;

    lRet = SQLConnect(szConn);
    if (lRet != 0) { SetTagWord("Query_Status", 2); return; }

    /* The CC_SP_ReadTags helper is exposed as SQL procedure call */
    /* Use the higher-level function SQLExec or the raw OLE DB handle */
    /* (see WinCC Information System -> C-Script -> OLE DB) */

    SQLDisconnect();
}
Field tip. C-script OLE DB support in WinCC V6.x is intentionally limited. The VBScript path documented in Section 6 is the supported way to run CC_SP_ReadTags from a picture action and is what the Siemens Information System ships as the reference example.

8. Common Error Codes and Troubleshooting

Table 5 - WinCC OLE DB / CC_SP_ReadTags error matrix
Symptom Error Code Likely Cause Corrective Action
Provider not registered 0x80040154 WinCCOLEDBProvider.dll not registered Run regsvr32 WinCCOLEDBProvider.dll or reinstall Connectivity Pack
No license 0x80040E1D Connectivity Pack license missing or expired Re-license with Automation License Manager; verify date/time on the server
Catalog not found 0x80004005 Wrong catalog name, archive has rolled Re-query dbo.CC_Configuration for current catalog
Tag not archived Empty result set Tag exists in process but is not configured for Tag Logging Enable Tag Logging for the tag in WinCC Explorer
Stored procedure not found 2812 Connectivity Pack not installed on target SQL instance Reinstall Connectivity Pack, run sp_helptext CC_SP_ReadTags
Performance very slow N/A Querying uncompressed segments or huge date range Reduce window to <= 24 h, add TIMESTEP=300, archive aging > 30 days
Connection works locally, fails remotely Network / DCOM errors SQL Browser service stopped, firewall blocks 1433/1434 Start SQL Browser, open ports, allow named pipes
Random Access Denied Win32 5 Antivirus has locked the MDF file Add \ArchiveManager\* to AV exclusion list

9. Verification Procedure

After deploying the picture, perform the following verification in order:

  1. Catalog enumeration. From a remote SQL client, run SELECT * FROM [<Catalog>].dbo.CC_Configuration with the connection string from Section 3. The result must include the archive server name and the active tag list.
  2. Stored procedure smoke test. Run the CC_SP_ReadTags call from SQL Server Management Studio with a known-good tag and a one-hour window. Expect a populated result set in less than 1 second for a single tag.
  3. Picture test. Open the picture in WinCC Runtime, enter a date that exists in the archive, click the button. Verify Query_ResultValue updates within 2 seconds and Query_Status reads 0.
  4. Negative test. Enter a date outside the archive retention. Query_Status must read 1, not 0, and Query_ResultValue must be 0.
  5. Error path. Stop the SQL service, click the button again. Query_Status must read 2 and the error must be caught; the runtime must not crash.
  6. Security check. From a non-admin Windows account, attempt the same query. It should be denied (or return an empty set), confirming the least-privilege configuration.
  7. CVE review. If the runtime is below WinCC V7.3, file a security ticket to apply the V7.3 fix or migrate. Document this in the change log per CVE-2014-4685.

10. Migration and Forward Compatibility

Customers using the V6.0 SP2 stack should be aware that:

  • WinCC V7.x and TIA Portal WinCC Professional retain the WinCC OLE DB Provider and the CC_SP_ReadTags family of stored procedures. The connection string format is unchanged. Scripts written for V6.2 SP2 work against V7.x with no modification.
  • V6.2 SP2 uses SQL Server 2005; V7.0 and later use SQL Server 2008 R2 or 2014. Backups of the V6.2 MDF/LDF files can be attached to a newer SQL Server, but the WinCC Archive Server must be reconfigured to recognize the new instance.
  • The V6.2 SP2 delivery release (ID 26636449) lists the Central Archive Server expansions (Section 2.7) that allow a single SQL Server to host multiple WinCC project catalogs. If you are running more than one project, plan capacity for the combined Tag Logging throughput.

11. Frequently Asked Questions

Do I need the Connectivity Pack to query the WinCC V6.0 SP2 database?

Yes. The WinCC OLE DB Provider and the CC_SP_ReadTags stored procedure are only installed and licensed by the Connectivity Pack. Without it, the provider returns error 0x80040E1D on the first Open call.

Where can I find the active catalog name at runtime?

Connect to the WinCC OLE DB Provider with no Catalog= parameter and run SELECT Catalog FROM dbo.CC_Configuration. The returned string is the current archive catalog and rotates with each runtime restart.

Can I aggregate 1-second data into 1-minute averages in one call?

Yes. Use CC_SP_ReadTags '<tag>','<from>','<to>',NULL,'Timestamp ASC','TIMESTEP=60,2,AGGREGATION=AVG'. The tolerance (2) lets the procedure interpolate if a 1-second value is missing in a bucket.

Is WinCC V6.0 SP2 affected by CVE-2014-4685?

Yes. CVE-2014-4685 applies to "SIMATIC WinCC before 7.3" and is described in the NVD record. Apply the WinCC V7.3 hotfix or migrate the runtime to a current TIA Portal WinCC Professional version.

Why does my query return no rows even though the tag is being archived?

The most common cause is a date range that lies outside the loaded segments. Run SELECT MIN(Timestamp), MAX(Timestamp) FROM dbo.TLG against the active catalog to confirm the data window, and shorten the user-entered range accordingly. A second common cause is a mis-spelled tag name; CC_SP_ReadTags is case-sensitive and requires the exact WinCC tag name.

Back to blog