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
autocommitflag,ADODB.Connectionruns outside a user transaction by default, soCREATE DATABASEworks 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.
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.
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 FunctionThe 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 SubDB_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 hereA 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 SubOBJECT_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
| Group | Columns | Purpose |
|---|---|---|
| Time | DT, TM | Event date/time and formatted time text |
| Identity | SQF_No, ChargeNo | Furnace and production-charge references |
| Transition | Event_From, Event_To | Previous and next process stages |
| Temperature | Temp_Set, Temp_Act | Setpoint and actual furnace temperature |
| Carbon potential | Cp_Set, Cp_Act | Target and measured process CP |
| Oil | Oil_Set, Oil_Act | Oil process values |
| Jacket | Jacket_Set, Jacket_Act | Jacket setpoint and actual value |
| Status | Fan_Status | Text 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 FunctionVerification 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.ExecuteA 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
| Problem | Likely cause | Action |
|---|---|---|
| Driver not found | ODBC driver not installed on the WinCC PC | Check Windows ODBC Data Source Administrator, update DRIVER_NAME |
| Server/instance not found | Wrong instance, SQL Browser, firewall or network issue | Verify SOFTWELL\WINCC and connectivity |
| CREATE DATABASE permission denied | WinCC runtime identity lacks server permission | Ask the DBA to provision the database or grant approved rights |
| Cannot open database requested by login | Database missing, offline or user not mapped | Verify creation state and grant database access |
| Table exists but schema is wrong | Existence check does not migrate columns | Run a reviewed schema comparison/migration |
| Runtime error 800A... in Global Script | ADODB object not created/closed correctly | Always 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
datetime2and carefully selecteddecimal(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- 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.
Test the master connection
Call ConnectDB("master") and close it without running any DDL.
Create or confirm the database
Run CreateDatabase() and verify DB_ID(N'SQF_DB') in SQL Server Management Studio.
Create and inspect the table
Run CreateEventTable(), then inspect columns and types under SQF_DB → Tables → dbo.tblEvent.
Prove idempotent behavior
Run Main() again and verify it keeps the existing database/table and returns the same verification result.
Related WinCC and SQL Server Tutorials
Continue through the Softwell WinCC–SQL Server learning path:
- WinCC VB Scripting fundamentals
- SQL Server reporting and data types for WinCC
- Create a SQL Server database and table with WinCC VBScript
- Compare: create a SQL Server database with Python pyodbc
- Insert data into SQL Server with Python
- Read SQL Server data into pandas
- Export SQL Server data to Excel
- Create a Python EXE for WinCC Excel reports
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.
