If you have a look at the line
cb.AppendFormat("on T.", tableName.Replace("]", "]]"))
You have not put a placeholder in the string for the value you are using. I would expect something like
cb.AppendFormat("on T.{0}", tableName.Replace("]", "]]"))
Similarly, you have used string concatenation in the line
cb.AppendFormat("on T." + columnName.Replace("]", "]]"))
so there was no point in using
AppendFormat
, you could have just used
Append
. Avoid string concatenation and do this instead:
cb.AppendFormat("on T.{0}", columnName.Replace("]", "]]"))
Now consider the line
cb.Append(Convert.ToString(" = "))
There is no need for the
Convert.ToString()
...
" = "
is already a string
When using AppendFormat you can include several variables in the format list to make the code a little tidier. For example you could replace
cb.AppendFormat(" [{0}] ", tableName.Replace("]", "]]"))
cb.Append("as T")
cb.AppendFormat(" using [{0}] ", tablename2.Replace("]", "]]"))
cb.Append("As S ")
with
cb.AppendFormat(" [{0}] as T using [{1}] as S", tableName.Replace("]", "]]"), tablename2.Replace("]", "]]"))
Without the benefit of any of the data in your list boxes it's a little difficult to comment on the rest of it. For example it is unclear why you are replacing
]
with
]]
etc
As the ON clause is repeated in both the update and the delete sql I would create that as a separate
StringBuilder
so you can re-use it.
This is the code I came up with, but you would have to check the output to make sure it is correct after plugging in your data from the list controls:
Dim cb2 As New StringBuilder("MERGE INTO ")
cb2.AppendFormat("{0} as T using {1} as S", tableName, tablename2)
Dim sbOn As New StringBuilder(" ON ")
Dim andRequired As Boolean = False
For Each item In CheckedListBox1.CheckedItems
If andRequired Then
sbOn.Append(" AND ")
End If
Dim columnName As String = item.ToString()
sbOn.AppendFormat("on T.[{0}] = S.[{1}]", columnName, columnName)
andRequired = True
Next
cb2.Append(sbOn.ToString())
cb2.Append("When Matched then Update Set T.[Birth] = S.[Birth];")
cb2.AppendFormat("DELETE T1 FROM [{0}] T1 JOIN [{1}] T2", tablename2, tableName)
cb2.Append(sbOn.ToString())
Debug.Print(cb2.ToString())
Note the trick I've used to make sure I don't get an extra
AND
in the
ON
clause