Updating a primary key in an MSI database (Modify method)

This blog entry provides an example of updating a primary key in an MSI database using the Modify method and VBScript. It follows on from the previous blog post which provided a tutorial on updating a registry value using the Modify method of an MSI database.

It forms part 7 of an 17-part series that explores how to use VBScript to manipulate MSI relational databases using the Windows Installer API. Throughout this series of tutorials, we identify the common issues that we encounter and the best practises that we use to overcome them.

Here we would change the SQL query to select our primary key value (in other words, we’re selecting the Registry column now instead of the Value column):

Dim regView : Set regView = oDatabase.OpenView("SELECT `Registry` FROM `Registry` WHERE `Registry` = 'SampleReg'")

and we would modify it like this:

regRecord.StringData(1) = "NewSampleReg"
regView.Modify msiViewModifyReplace, regRecord

So in full it becomes:

'create 2 constants - one for when we want to just query the MSI (read) and one for when we want to make changes (write)
Const msiOpenDatabaseModeReadOnly = 0
Const msiOpenDatabaseModeTransact = 1
Const msiViewModifyInsert = 1
Const msiViewModifyUpdate = 2
Const msiViewModifyDelete = 6
Const msiViewModifyReplace = 4
'create WindowsInstaller.Installer object
Dim oInstaller : Set oInstaller = CreateObject("WindowsInstaller.Installer")
'open the MSI (the first argument supplied to the vbscript)
Dim oDatabase : Set oDatabase = oInstaller.OpenDatabase(WScript.Arguments(0),msiOpenDatabaseModeTransact) 
Dim sql : sql = "SELECT `Registry` FROM `Registry` WHERE `Registry` = 'SampleReg'"
'create a view of the registry we want to see
Dim regView : Set regView = oDatabase.OpenView(sql)
'execute the query
regView.Execute 
'fetch the first row of data (if there is one!)
Dim regRecord : Set regRecord = regView.Fetch
'whilst we've returned a row and therefore regRecord is not Nothing
While Not regRecord Is Nothing
regRecord.StringData(1) = "NewSampleReg" 
regView.Modify msiViewModifyReplace, regRecord
'go and fetch the next row of data	
Set regRecord = regView.Fetch
Wend
oDatabase.Commit
regView.Close
Set regView = Nothing
Set regRecord = Nothing
Set oDatabase = Nothing
Set oInstaller = Nothing

Note that this essentially won’t update that particular row. Instead it will delete the current row, and insert the new row containing the new primary key value.

Thanks for reading about updating a primary key in an MSI database using the Modify method and VBScript. Next you can find out how to delete a registry value in an MSI database using the Modify method and VBScript.