WinCC VBScript · SQL Server · Technical Blog

Create a SQL Server Database and Table with WinCC VBScript (ADODB)

A complete ADODB workflow that creates SQF_DB from master, reconnects to the new database, creates dbo.tblEvent only when required, and verifies both objects — the WinCC scripting equivalent of the Python + pyodbc lab.

SQL database practical Corrected VBScript / ADODB code Create-only-if-missing Furnace event schema

Lab Overview

Lab 3 of 8Estimated time: 45 minutesDifficulty: Intermediate

Prerequisites / What You’ll Need

  • WinCC project with Global Script (VBS) enabled
  • SQL Server instance with database-creation permission
  • Microsoft ODBC Driver (SQL Server / ODBC Driver 17)
Quick answer

Connect to SQL Server's existing master database with an ADODB.Connection, run CREATE DATABASE only when DB_ID() returns null, close that connection, then connect to SQF_DB and create dbo.tblEvent only when OBJECT_ID() is null. Verify the resulting object ID, then insert rows using a parameterized ADODB.Command.

  • You cannot initially connect to a database that does not exist.
  • Unlike pyodbc's autocommit flag, ADODB.Connection runs outside a user transaction by default, so CREATE DATABASE works without extra setup.
  • Existence checks make reruns non-destructive, but they do not upgrade an old or incorrect schema.

WinCC SQL Server Database Creation: What You Will Build

This page covers the exact intent behind "create SQL Server database using WinCC VBScript": connect to an existing master database, run CREATE DATABASE outside a user transaction, reconnect to the new database, create a table only when missing, and verify the result.

Related Search Topics

ADODB create database SQL Server · WinCC VBScript create SQL Server table · CREATE DATABASE WinCC ADODB · connect WinCC VBScript to SQL Server master database

WinCC VBScript Database-Creation Workflow

WinCC talks to SQL Server through ADODB, the COM automation library used by classic VB/VBScript, rather than a Python driver like pyodbc. The logic is identical in spirit but the objects and syntax differ. Database creation and table creation require separate connections because the target database is unavailable until the first operation finishes.

1. MasterConnect to an existing database
2. Create DBEnsure SQF_DB exists
3. ReconnectOpen SQF_DB
4. Create tableEnsure dbo.tblEvent exists
5. VerifyRead database/object identity

DDL—Data Definition Language—creates or changes database objects. CREATE DATABASE defines a database; CREATE TABLE defines a table and its columns. This script changes server state and should be executed only by an authorized user, from a WinCC Global Script action, against the intended SQL Server instance.

2. Requirements and Permissions

  • WinCC project with Global Script (VBS) enabled.
  • Microsoft ODBC Driver installed on the WinCC PC (e.g. "SQL Server" or "ODBC Driver 17 for SQL Server").
  • Network access to SOFTWELL\WINCC.
  • Windows authentication (Trusted Connection) enabled for the WinCC runtime identity.
  • Server-level permission to create a database and database-level permission to create a table.
Use least privilege: database creation is an administrative operation. In production, a DBA normally provisions the database and grants the WinCC runtime account only the runtime permissions it needs. Do not run a training script using an unrestricted administrator account.

3. Build a Reusable Connection Helper

Function ConnectDB(databaseName)
    Dim conn, connString
    connString = "Driver={" & DRIVER_NAME & "};" & _
                 "Server=" & SERVER & ";" & _
                 "Database=" & databaseName & ";" & _
                 "Trusted_Connection=Yes;"

    Set conn = CreateObject("ADODB.Connection")
    conn.ConnectionTimeout = 15
    conn.Open connString
    Set ConnectDB = conn
End Function

The helper accepts the database name so the same connection settings can serve both stages. The raw server string preserves the named-instance backslash. Unlike pyodbc, ADODB has no separate autocommit argument — a plain connection is not inside a user transaction unless you explicitly call BeginTrans.

Create a SQL Server Database from master with VBScript

Sub CreateDatabase()
    Dim conn, sql
    Set conn = ConnectDB("master")

    sql = "IF DB_ID(N'" & DATABASE_NAME & "') IS NULL " & _
          "BEGIN " & _
          "  CREATE DATABASE [" & DATABASE_NAME & "]; " & _
          "END;"

    conn.Execute sql
    conn.Close
    Set conn = Nothing
End Sub

DB_ID(N'SQF_DB') returns the database ID when the database exists and NULL otherwise. The conditional prevents a second run from raising "database already exists" — the same guard used in the Python version.

Because ADODB is not inside an explicit transaction by default, CREATE DATABASE completes immediately without any special connection mode.

5. Reconnect to the New Database

Set conn = ConnectDB(DATABASE_NAME)
' CREATE TABLE runs here

A connection stays tied to the database it was opened against. After creating SQF_DB from master, open a fresh ADODB.Connection whose Database= value is SQF_DB. This also gives a clean failure point if database creation was not successful or access was not granted.

Create a SQL Server Table with VBScript

Sub CreateEventTable()
    Dim conn, sql
    Set conn = ConnectDB(DATABASE_NAME)

    sql = "IF OBJECT_ID(N'" & TABLE_NAME & "', N'U') IS NULL " & _
          "BEGIN " & _
          "  CREATE TABLE " & TABLE_NAME & " (" & _
          "    DT          datetime      NOT NULL," & _
          "    TM          varchar(10)   NULL," & _
          "    SQF_No      int           NULL," & _
          "    ChargeNo    varchar(50)   NULL," & _
          "    Event_From  varchar(100)  NULL," & _
          "    Event_To    varchar(100)  NULL," & _
          "    Temp_Set    float         NULL," & _
          "    Temp_Act    float         NULL," & _
          "    Cp_Set      float         NULL," & _
          "    Cp_Act      float         NULL," & _
          "    Oil_Set     float         NULL," & _
          "    Oil_Act     float         NULL," & _
          "    Jacket_Set  float         NULL," & _
          "    Jacket_Act  float         NULL," & _
          "    Fan_Status  varchar(10)   NULL" & _
          "  );" & _
          "END;"

    conn.Execute sql
    conn.Close
    Set conn = Nothing
End Sub

OBJECT_ID(..., N'U') asks for an object ID specifically for a user table. The condition protects an existing table from being overwritten. It does not compare the existing table's columns or types; schema migration must be handled separately.

7. Understand the Furnace Event Columns

GroupColumnsPurpose
TimeDT, TMEvent date/time and formatted time text
IdentitySQF_No, ChargeNoFurnace and production-charge references
TransitionEvent_From, Event_ToPrevious and next process stages
TemperatureTemp_Set, Temp_ActSetpoint and actual furnace temperature
Carbon potentialCp_Set, Cp_ActTarget and measured process CP
OilOil_Set, Oil_ActOil process values
JacketJacket_Set, Jacket_ActJacket setpoint and actual value
StatusFan_StatusText status such as ON/OFF

For a production design, consider datetime2 instead of legacy datetime, decimal(p,s) instead of approximate float where exact decimal behavior matters, a primary key, defaults/check constraints, and a single timestamp rather than duplicated DT/TM representations.

8. Verify Objects and Insert a Row

Function VerifyObjects()
    Dim conn, rs, sql
    Set conn = ConnectDB(DATABASE_NAME)

    sql = "SELECT DB_NAME() AS DatabaseName, " & _
          "OBJECT_ID(N'" & TABLE_NAME & "', N'U') AS TableObjectId;"

    Set rs = conn.Execute(sql)
    VerifyObjects = Not IsNull(rs.Fields("TableObjectId").Value)

    rs.Close
    conn.Close
End Function

Verification confirms both the active database context and the table object ID. Once verified, insert rows with a parameterized ADODB.Command — never by concatenating live tag values into SQL text:

Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = conn
cmd.CommandText = "INSERT INTO " & TABLE_NAME & _
    " (DT, TM, SQF_No, ChargeNo, ...) VALUES (GETDATE(), CONVERT(varchar(10), GETDATE(), 108), ?, ?, ...);"
cmd.Parameters.Append cmd.CreateParameter("SQF_No", 3, 1, , sqfNo)
' ... more parameters ...
cmd.Execute

A complete deployment check should additionally query sys.columns for types, lengths, nullability and constraints.

9. Identifier Safety and Idempotent Reruns

Parameters (?) can represent data values, but not database/table identifiers — true in ADODB exactly as in pyodbc. The database name is therefore interpolated into DDL. This is safe only because DATABASE_NAME is a trusted script constant. Never accept an unchecked database name from an operator screen, recipe file or external input and insert it into SQL text.

The checks make this script create-if-missing: rerunning it on every WinCC startup leaves existing objects in place. That is useful, but not the same as schema versioning. If an existing tblEvent lacks a column or uses the wrong type, this script reports success without correcting it. Use reviewed migration scripts for schema changes.

10. Complete Corrected WinCC VBScript Template

Option Explicit

Dim SERVER, DATABASE_NAME, DRIVER_NAME, TABLE_NAME
SERVER        = "SOFTWELL\WINCC"
DATABASE_NAME = "SQF_DB"
DRIVER_NAME   = "SQL Server"
TABLE_NAME    = "dbo.tblEvent"

Function ConnectDB(databaseName)
    Dim conn, connString
    connString = "Driver={" & DRIVER_NAME & "};Server=" & SERVER & _
                 ";Database=" & databaseName & ";Trusted_Connection=Yes;"
    Set conn = CreateObject("ADODB.Connection")
    conn.ConnectionTimeout = 15
    conn.Open connString
    Set ConnectDB = conn
End Function

Sub CreateDatabase()
    Dim conn : Set conn = ConnectDB("master")
    conn.Execute "IF DB_ID(N'" & DATABASE_NAME & "') IS NULL BEGIN CREATE DATABASE [" & DATABASE_NAME & "]; END;"
    conn.Close : Set conn = Nothing
End Sub

Sub CreateEventTable()
    Dim conn : Set conn = ConnectDB(DATABASE_NAME)
    conn.Execute "IF OBJECT_ID(N'" & TABLE_NAME & "', N'U') IS NULL BEGIN CREATE TABLE " & TABLE_NAME & _
        " (DT datetime NOT NULL, TM varchar(10) NULL, SQF_No int NULL, ChargeNo varchar(50) NULL, " & _
        "Event_From varchar(100) NULL, Event_To varchar(100) NULL, Temp_Set float NULL, Temp_Act float NULL, " & _
        "Cp_Set float NULL, Cp_Act float NULL, Oil_Set float NULL, Oil_Act float NULL, " & _
        "Jacket_Set float NULL, Jacket_Act float NULL, Fan_Status varchar(10) NULL); END;"
    conn.Close : Set conn = Nothing
End Sub

Function VerifyObjects()
    Dim conn, rs
    Set conn = ConnectDB(DATABASE_NAME)
    Set rs = conn.Execute("SELECT DB_NAME() AS DatabaseName, OBJECT_ID(N'" & TABLE_NAME & "', N'U') AS TableObjectId;")
    VerifyObjects = Not IsNull(rs.Fields("TableObjectId").Value)
    rs.Close : conn.Close
End Function

Sub Main()
    On Error Resume Next
    CreateDatabase()
    CreateEventTable()
    If VerifyObjects() Then
        MsgBox "Database and table verified successfully.", vbInformation
    Else
        MsgBox TABLE_NAME & " was not created.", vbCritical
    End If
    On Error Goto 0
End Sub

11. Troubleshooting and Design Improvements

ProblemLikely causeAction
Driver not foundODBC driver not installed on the WinCC PCCheck Windows ODBC Data Source Administrator, update DRIVER_NAME
Server/instance not foundWrong instance, SQL Browser, firewall or network issueVerify SOFTWELL\WINCC and connectivity
CREATE DATABASE permission deniedWinCC runtime identity lacks server permissionAsk the DBA to provision the database or grant approved rights
Cannot open database requested by loginDatabase missing, offline or user not mappedVerify creation state and grant database access
Table exists but schema is wrongExistence check does not migrate columnsRun a reviewed schema comparison/migration
Runtime error 800A... in Global ScriptADODB object not created/closed correctlyAlways set Nothing after Close; check with On Error Resume Next

Recommended production upgrades

  • Use a DBA-managed deployment account separate from the WinCC runtime account.
  • Add a primary key such as Event_ID bigint IDENTITY.
  • Use datetime2 and carefully selected decimal(p,s) precision/scale.
  • Add check constraints or reference tables for valid fan and process-stage values.
  • Create useful indexes only after studying read/write patterns.
  • Store the connection string securely and validate every identifier against an allowlist.
  • Use a migration tool or versioned SQL scripts for future schema changes.

Hands-On Lab: Create and Verify SQF_DB

Hands-on
Before you start
  • Use an approved local or training SQL Server instance.
  • Confirm authorization to create databases and tables.
  • Confirm the ODBC driver is installed on the WinCC PC.
  • Estimated time: 20 minutes.
1

Test the master connection

Call ConnectDB("master") and close it without running any DDL.

The authorized Windows identity connects to the intended instance.
2

Create or confirm the database

Run CreateDatabase() and verify DB_ID(N'SQF_DB') in SQL Server Management Studio.

SQF_DB exists and a second run does not attempt duplicate creation.
3

Create and inspect the table

Run CreateEventTable(), then inspect columns and types under SQF_DB → Tables → dbo.tblEvent.

All 15 expected columns are present with the configured types and nullability.
4

Prove idempotent behavior

Run Main() again and verify it keeps the existing database/table and returns the same verification result.

The rerun completes without deleting data or recreating objects.

Related WinCC and SQL Server Tutorials

Continue through the Softwell WinCC–SQL Server learning path:

Frequently asked questions

Why connect to master first?

The target database does not exist yet, so the initial connection must use an existing database. After creation, open a new ADODB.Connection to SQF_DB.

Does ADODB need an autocommit flag like pyodbc?

No. A plain ADODB.Connection is not inside an explicit transaction unless BeginTrans is called, so CREATE DATABASE runs without extra setup — unlike pyodbc, which requires autocommit=True.

Will the script overwrite an existing database or table?

No. DB_ID() and OBJECT_ID() checks create each object only when missing. However, they do not validate or upgrade an existing table schema.

Reviewed by Bhawesh Kumar SinghIndustrial Automation Trainer and Industry 4.0 Consultant · Softwell Automation · 21+ years industry experience

Get the WinCC VBScript + SQL reporting syllabus

Share your details—a Softwell advisor will contact you with batch dates, fees and project-practice options.

No spam. Used only to share course details for this enquiry.

Build reliable WinCC and SQL Server projects

Join live online, Pune classroom or corporate Industry 4.0 training.

Request Course Details
Verified learning pathway

Discuss Python SQL Server Training

Explore practical curriculum, software, hardware and batch options for this technology.

Content reviewed: 2 August 2026

☎ Call WhatsApp ✉ Email Enquire Now