Excel VBA updating SQL Table - permissions issues - sql-server

I am connecting to a SQL table via an Excel VBA script using using SQL Server vs Windows Authentication as we're creating a generic update application to be used by several different users. If I log into SQL Server Management Studio with the generic ID/pswd and SQL Server Authentication, I can successfully insert and delete rows. When I use the VBA script, I receive an error indicating that the INSERT or DELETE permission was denied. The VBA script works successfully against the same table in a different schema, but fails going against this schema. I am assuming it's something in the SQL environment, as it seems like it's forced to Windows Authentication regardless of how I make the connection. Any help would be greatly appreciated.
Updates:
Thanks for the responses. I hope this additional information helps. We are on SQL Server 15.04102.2, and I am using SQL Server Authentication with a generic application ID and PSWD that has update permissions (my individual windows account only has select permissions)
As I indicated in my initial post, if I execute this code against one test environment, the DELETE and INSERT work perfectly. When I execute it against a different environment, the connection is made, but I get the permissions error on the DELETE and INSERT. If I use the exact same credentials and use SQL Server Authentication to go directly to that environment, I can successfully execute the DELETE and INSERT statements.
Here is the error I receive on the DELETE statement. A similar error is received on the INSERT statement if I bypass the delete for a new add.
Error -2147217911 (The DELETE permission was denied on the object
‘BCG_CGS_DETAILS’, database ‘xxxxxxcustom’, schema ‘dbo’.) in
procedure Export CGS to SQL. sSQL = delete dbo.BCG_CGS_DETAILS where
[CGSNUM]= ‘CGS-xxxxx’ AND [PDPD_ID]= ‘xxxxx’ AND EFF_DT=’7/1/2021’
Here is the code I am executing.
Sub Export_CGS_to_SQL()
Dim cnn
Dim rst
Dim sSQL As String
Dim iRow As Integer
Dim sLINE, sCategory, sBCBSNC_Medical_Policy, sBCBSNC_Standard_Provisions As String
Dim sIn_Network_VALUE, sIn_Network_Type_of_payment, sIn_Network_Detail As String
Dim sOut_of_Network_VALUE, sOut_of_Network_Type_of_payment, sOut_of_Network_Detail As String
Dim sCustomized, sCGSNUM, sPDPD_ID, sEFF_DT As String
Dim lLastrow As Long
Dim sServer, sTable, sDatabase, sConnection As String
On Error GoTo errHandler
With Sheets("CGS Data")
sCGSNUM = .Cells(2, 12)
sPDPD_ID = .Cells(2, 13)
sEFF_DT = .Cells(2, 14)
If sCGSNUM = "" Or sPDPD_ID = "0" Or sEFF_DT = "" Then
MsgBox "One or more required fields is blank. Please make sure that the Product ID and Effective date are set correctly on the MISC tab, and that the CGS Number exists for row A06c on the Client Profile tab"
Exit Sub
End If
lLastrow = Cells(Rows.Count, 1).End(xlUp).Row
sServer = Worksheets("MACRO_DATA").Range("B6").Value
sTable = Worksheets("MACRO_DATA").Range("B7").Value
sDatabase = Worksheets("MACRO_DATA").Range("B8").Value
sConnection = Worksheets("MACRO_DATA").Range("F5").Value
'Create a new Connection object
Set cnn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
If cnn.State <> 1 Then
sSQL = "Provider=SQLOLEDB;Data Source=" & sServer & "; Initial Catalog=" & sDatabase & ";" & sConnection & "; Trusted_Connection=yes"
cnn.Open (sSQL)
End If
Set rst.ActiveConnection = cnn
sSQL = "delete " & sTable & " where [CGSNUM]= '" & sCGSNUM & "' AND [PDPD_ID]= '" & sPDPD_ID & "' AND EFF_DT= '" & sEFF_DT & "'"
cnn.Execute sSQL
For iRow = 2 To lLastrow
sLINE = .Cells(iRow, 1)
If sLINE <> "" Then
sCategory = .Cells(iRow, 2)
sBCBSNC_Medical_Policy = .Cells(iRow, 3)
sBCBSNC_Standard_Provisions = .Cells(iRow, 4)
sIn_Network_VALUE = .Cells(iRow, 5)
sIn_Network_Type_of_payment = .Cells(iRow, 6)
sIn_Network_Detail = .Cells(iRow, 7)
sOut_of_Network_VALUE = .Cells(iRow, 8)
sOut_of_Network_Type_of_payment = .Cells(iRow, 9)
sOut_of_Network_Detail = .Cells(iRow, 10)
sCustomized = .Cells(iRow, 11)
sCGSNUM = .Cells(iRow, 12)
sPDPD_ID = .Cells(iRow, 13)
sEFF_DT = .Cells(iRow, 14)
'insert row into sDatabase
sSQL = "insert into " & sTable & "([LINE],[Category],[BCBSNC Medical Policy],[BCBSNC Standard Provisions],[In-Network_VALUE]," _
& "[In-Network_Type of payment],[In-Network Detail],[Out-of-Network_VALUE],[Out-of-Network_Type of payment],[Out-of-Network_Detail]," _
& "[Customized],[CGSNUM],[PDPD_ID],[EFF_DT])" _
& "values ('" & sLINE & "', '" & sCategory & "', '" & sBCBSNC_Medical_Policy & "', '" & sBCBSNC_Standard_Provisions & "', '" _
& sIn_Network_VALUE & "', '" & sIn_Network_Type_of_payment & "', '" & sIn_Network_Detail & "', '" & sOut_of_Network_VALUE & "', '" _
& sOut_of_Network_Type_of_payment & "', '" & sOut_of_Network_Detail & "', '" & sCustomized & "', '" & sCGSNUM & "', '" _
& sPDPD_ID & "', '" & sEFF_DT & "')"
cnn.Execute sSQL
End If
Next iRow
MsgBox "CGS Data successfully exported to " & sTable, vbInformation
cnn.Close
Set cnn = Nothing
End With
Exit Sub
errHandler:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export CGS to SQL. sSQL = " & sSQL
cnn.Close
Set cnn = Nothing
End Sub

Related

Export Excel to SQL without duplicate values

I have success making a connection between Excel and SQL with managing to add records from Excel cells to SQL database table and this is the tutorial i did:
Export data from Excel to SQL Server
a (Sign up form) i made in excel Sign up form i made , and i manage to make a Macro to (Sign Up) button to transfer the data into the SQL database and this is the code for a reference :
Sub connect()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
' Dim sCustomerId, sFirstName, sLastName As String
With Sheets("Sheet2")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=seshbones\bones;Initial Catalog=fadi;Integrated Security=SSPI;"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
Name = .Cells(iRowNo, 1)
Location = .Cells(iRowNo, 2)
Age = .Cells(iRowNo, 3)
ID = .Cells(iRowNo, 4)
Mobile = .Cells(iRowNo, 5)
Email = .Cells(iRowNo, 6)
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Execute "insert into dbo.test (Name, Location, Age, ID, Mobile, Email) values ('" & Name & "', '" & Location & "', '" & Age & "', '" & ID & "', '" & Mobile & "', '" & Email & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Customers imported."
conn.Close
Set conn = Nothing
End With
me in the table
End Sub
I want to make a restriction code to not duplicate the same Username in the table, for example if the customer enters a (Username) in excel cell and pressed (SignUP) there must have a function that check the SQL database and check the Username is already taken and refuse to make the exporting and message box appears "User is already taken" i hope you got my point.
Thank you for your help guys i added the error handler code to my project, so if there a duplicate records in my database it will prevent my program from shutting down and simply warn the user "Username Already taken" this is my how i fix the code :
Sub Connect()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
' Dim sCustomerId, sFirstName, sLastName As String
'Error handler
On Error GoTo ErrHandler:
With Sheets("Sheet2")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=seshbones\bones;Initial Catalog=fadi;Integrated Security=SSPI;"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
Name = .Cells(iRowNo, 1)
Location = .Cells(iRowNo, 2)
Age = .Cells(iRowNo, 3)
ID = .Cells(iRowNo, 4)
Mobile = .Cells(iRowNo, 5)
Email = .Cells(iRowNo, 6)
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Execute "insert into dbo.test (Name, Location, Age, ID, Mobile, Email) values ('" & Name & "', '" & Location & "', '" & Age & "', '" & ID & "', '" & Mobile & "', '" & Email & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Customers imported."
conn.Close
Set conn = Nothing
End With
Exit Sub
ErrHandler:MsgBox "Username Already taken" End Sub

Insert new records only into SQL Table Using VBA

I have an Excel workbook with the below code -
Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sFirstName, sLastName As String
With Sheets("Sheet1")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;" & _
"Data Source=server1;" & _
"Initial Catalog=table1;" & _
"User ID=user1; Password=pass1"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
sFirstName = .Cells(iRowNo, 1)
sLastName = .Cells(iRowNo, 2)
'Generate and execute sql statement
' to import the excel rows to SQL Server table
conn.Execute "Insert into dbo.Customers (FirstName, LastName) " & _
"values ('" & sFirstName & "', '" & sLastName & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Customers imported."
conn.Close
Set conn = Nothing
End With
End Sub
This opens up a connection to my database and inputs the values from the stated columns.
The primary key is an incremental key on the database. The problem is it will copy ALL values.
I'd like to add new rows of data into the Excel Sheet and only insert those rows that don't already exist.
I've tried different methods ('merge', 'if exist', if not exist', etc.) but I can't get it right.
The solution has to be through VBA. Setting up a link using SSMS is not an option.
I understand that it may be possible to use temporary tables and then trigger a procedure which performs the merge but I want to look into that as a last resort. Haven't read up on it yet (making my way through my MS SQL bible book) but I'm hoping it won't be necessary.
---Update from #Kannan's answer---
New portion of VBA -
conn.Execute "IF EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" & sFirstName & "' and LastName = '" & sLastName & "') " & _
"THEN UPDATE dbo.customers SET WHERE Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' " & _
"ELSE INSERT INTO dbo.Customers (FirstName, LastName) " & _
"VALUES ('" & sFirstName & "', '" & sLastName & "')"
This returns error 'Incorrect syntax near the keyword 'THEN'.
Your SQL query isn't quite right - there is no THEN in a SQL IF.
Also, you don't need to do anything if it does exist, so just use if not exists.
"IF NOT EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" & sFirstName & "' and LastName = '" & sLastName & "') " & _
"INSERT INTO dbo.Customers (FirstName, LastName) " & _
"VALUES ('" & sFirstName & "', '" & sLastName & "')"
This should do it for you.
Sub Button_Click()
'TRUSTED CONNECTION
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim strFirstName, strLastName As String
Dim server, username, password, table, database As String
With Sheets("Sheet1")
server = .TextBox1.Text
table = .TextBox4.Text
database = .TextBox5.Text
If con.State <> 1 Then
con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
'con.Open
End If
'this is the TRUSTED connection string
Set rs.ActiveConnection = con
'delete all records first if checkbox checked
If .CheckBox1 Then
con.Execute "delete from tbl_demo"
End If
'set first row with records to import
'you could also just loop thru a range if you want.
intImportRow = 10
Do Until .Cells(intImportRow, 1) = ""
strFirstName = .Cells(intImportRow, 1)
strLastName = .Cells(intImportRow, 2)
'insert row into database
con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
intImportRow = intImportRow + 1
Loop
MsgBox "Done importing", vbInformation
con.Close
Set con = Nothing
End With
Exit Sub
errH:
MsgBox Err.Description
End Sub
Add a reference to:
Microsoft ActiveX Data Objects 2.8 Library
FYI, my sheet looks like this.
You can use sql query like this:
IF Exists ( Select 1 from dbo.customers where Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' THEN Update dbo.customers set --other columns where Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "'
ELSE Insert into dbo.Customers (FirstName, LastName) " & _
"values ('" & sFirstName & "', '" & sLastName & "')"
Not sure about the syntax for excel and C#, you can correct that similar to this query

Query will not update SQL Server

In the below code, my second query will not insert into the SQL database, but the first one will update. I can copy the query (from the msgbox i added for testing) and paste it in SQL Server Management Studio, and it will execute fine. I also do not get any error messages back from SQL, though i'm not sure if that code is correct (it was copied + pasted from another source). Also, can i simplify the code to pass both queries at the same time?
Dim Conn As New System.Data.SqlClient.SqlConnection 'sql server datastream connection
Dim Cmd As New System.Data.SqlClient.SqlCommand 'sql command vars
Dim SqlQuery As String 'string var used to hold various SQL queries
Dim data As System.Data.SqlClient.SqlDataReader 'datareader object variable
Dim MVDataset As New DataSet
Dim MVDatatable As DataTable
Dim MVDatarow As DataRow
Private Sub MVUpdateButton_Click(sender As Object, e As EventArgs) Handles MVUpdateButton.Click
vbyn = MsgBox("Are you sure you want to update Tally Sheet Master Variables?" & vbCrLf & vbCrLf & "Changes to these variables will change the functionality of the Tally Sheet!", vbYesNo, )
Try
Select Case vbyn
Case vbNo
GoTo MVTableUpdateBypass
Case vbYes
'get new data from textboxes
Vers = TextBox1.Text
If TextBox2.Text = True Then
Testing = 1
Else
Testing = 0
End If
FlatFeeCharge = TextBox3.Text
PrepricingCharge = TextBox4.Text
SendMailAcct = TextBox5.Text
SendMailPW = TextBox6.Text
TestingEmail = TextBox7.Text
PrePricingEmail = TextBox8.Text
ImperataEmail = TextBox9.Text
'update existing active row to mark inactive
SqlQuery = "Update MasterVars set Active = 0 where PKEY = " & PKEY & ";"
MsgBox(SqlQuery)
If Conn.State = ConnectionState.Closed Then
Conn.ConnectionString = "Data Source=SQL01;Initial Catalog=TallySheet;Integrated Security=SSPI;"
End If
Conn.Open()
Dim MVDataAdapter As New SqlDataAdapter(SqlQuery, Conn)
Dim MVUpdateCommand As SqlCommand
MVUpdateCommand = New SqlCommand(SqlQuery)
MVDataAdapter.UpdateCommand = MVUpdateCommand
'insert new active row
SqlQuery = "Insert into MasterVars (Vers, Testing, FlatFeeCharge, PrePricingCharge, SendMailAcct, SendMailPW, TestingEmail, PrePricingEmail, ImperataEmail, DTS, UserName, Active) Values (" & "'" & Vers & "', " & Testing & ", '" & FlatFeeCharge & "'" & ", '" & PrepricingCharge & "'" & ", '" & SendMailAcct & "'" & ", '" & SendMailPW & "'" & ", '" & TestingEmail & "'" & ", '" & PrePricingEmail & "'" & ", '" & ImperataEmail & "'" & ", '" & Date.Now & "'," & "'QGDOMAIN\" & Environment.UserName & "'," & 1 & ");"
MsgBox(SqlQuery)
Dim MVInsertCommand As SqlCommand
MVInsertCommand = New SqlCommand(SqlQuery)
MVDataAdapter.InsertCommand = MVInsertCommand
MVDataAdapter.Fill(MVDataset, "MasterVars")
End Select
Catch ex As SqlException
Dim i As Integer
Dim errormessages As String
errormessages = ""
For i = 0 To ex.Errors.Count - 1
errormessages = errormessages & " " & ("Index #" & i.ToString() & ControlChars.NewLine _
& "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
& "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
& "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
& "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
Next i
Console.WriteLine(errorMessages.ToString())
End Try
'reload form with updated variables
Conn.Close()
Conn.Dispose()
MVTableUpdateBypass:
End Sub
The Fill method of the SqlDataAdapter executes the SelectCommand not the UpdateCommand or the InsertCommand. In any case these two commands (and the DeleteCommand) are executed when you call the Update method of the adapter.
Moreover the Update method runs the commands looking for rows changed/added/deleted in the DataTable/DataSet retrieved by the SelectCommand and works only for those rows.
But you don't need an SqlDataAdapter to execute your two queries. You should simply construct an SqlCommand with both texts separated by a semicolon and call ExecuteNonQuery
SqlQuery = "Update MasterVars set Active = 0 where PKEY = #key;" & _
"Insert into MasterVars (Vers, Testing, .....) VALUES (#p1, #o2, ....)"
Using Conn = New SqlConnection("Data Source=SQL01;......")
Using cmd = New SqlCommand(SqlQuery, Conn)
Conn.Open()
cmd.Parameters.Add("#key", SqlDbType.Int).Value = PKEY
cmd.Parameters.Add("#p1", SqlDbType.NVarChar).Value = vers
cmd.Parameters.Add("#p2", SqlDbType.Int).Value = testing
... and so on with other parameters ....
cmd.ExecuteNonQuery()
End Using
End Using
In this incomplete example (too many parameters to write down) I have concatenated the two sql texts in a single string and prepared it with parameter placeholders. Then I build the parameter collection with the exact datatypes required by your table and finally call ExecuteNonQuery to run everything on the database side.
Notice that is not needed to keep global objects like the connection or the command. It is always better to create a local variable, use and destroy it when done. In particular disposable objects like the connection and the command should always created in a Using block

Missing semicolon (;) at the end of SQL statement when insert data to ms access table

this is my code
dim straccess as string
Do While Not rso.EOF
30 straccess = "INSERT INTO [test] ([nik],[nama]) VALUES ('" & rso.Fields(0)
& "' ,'" & rso.Fields(1) & "' ) where [nama]= '" _
& rso.Fields(0) & "';"
cna.Execute straccess
Loop
got error on line 30 when insert data.
im type this code in vb6 n want to insert data from oracle database/table to msaccess database/table. i already hv connection to oracle table n ms access. And now I try to insert data into MS Access table based data in oracle table
my table name in ms access is TEST and my table name in empmasterepms.
this is my all code .
Dim vstr As String
Dim filename As String
Dim straccess As String
Option Explicit
Const ORACLEQUERY As String = "select empcode,empname from empmasterepms order by EMPNAME"
Dim cno As New ADODB.Connection
Dim cna As New ADODB.Connection
Dim rso As New ADODB.Recordset
Dim rsa As New ADODB.Recordset
Private Sub btnload_Click()
On Error GoTo Error_Handler
'-----------------Connection to Oracle
cno.Open "Provider=msdaora;Data Source=192.168.0.15:1521/EPMS;User Id=EPMS_TRXI;Password=epmse292014;"
rso.CursorType = adOpenStatic
rso.CursorLocation = adUseClient
rso.LockType = adLockOptimistic
rso.Open ORACLEQUERY, cno, , , adCmdText
Set dg1.DataSource = rso
------- connect to msaccess
cna.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & vstr
rso.MoveFirst
Do While Not rso.EOF
30 straccess = "Update test SET [nik] = '" & rso.Fields(0).Value & "' ,[nama] = '" & rso.Fields(1).Value & "' WHERE [nama] = '" & rso.Fields(1).Value & "';"
cna.Execute straccess
rso.MoveNext
Loop
MsgBox "Done"
cno.Close
Set cno = Nothing
Set cna = Nothing
Exit Sub
Error_Handler:
MsgBox Erl & ":" & Err.Number & ":" & Err.Description
Debug.Print (straccess)
end sub
Remove the Where statement:
30 straccess = "INSERT INTO [test] ([nik],[nama]) VALUES ('" & rso.Fields(0).Value & "','" & rso.Fields(1).Value & "');"

Excel DB connection: insert, update & delete? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I used the DATA-From Other Sources-From SQL Server controls to import a database table into my Excel workbook. It looks perfect, and refreshing data works like a charm.
However, whenever I make any changes to the table (editing, inserting or deleting rows), I cannot seem to find a way to push these changes to the database. This makes me wonder whether this is actually possible.
Can anybody tell me how to do this, or confirm that this is not supported?
When you make a 'live' table in Excel by linking to an external data source like you have described in this question, Excel manages this by using a QueryTable object behind the scenes.
QueryTable objects have the ability to be refreshed on demand, and to refresh on a periodic schedule defined by the user.
QuertyTable objects are NOT bi-directional. They can be used to import data into Excel, but not to write changes back to the data source.
QueryTable objects can be manipulated from VBA.
Custom VBA code can be written to automatically write to a data source any changes made by a user to a table. But this absolutely requires writing code... it is not a simple option that you can select from the Excel user interface for your table.
Can anybody tell me how to do this, or confirm that this is not supported?
Insert, update, and delete are not supported from the Excel user interface.
Since you didn't have an exact goal other than ,.. Can you, how to ? let me just dump my code that i KNOW works because i use it all the time. This is part of a custom ribbon that is on 20+ computer so they can update/merge their sales information into out database. This should help you out feel free to ask some questions. Basically how it works is creates SQL command, that creates a temp table then merge/updates against our database
Dim adoCN As ADODB.Connection
Dim sConnString As String
Dim sSQL, sSQLMerge As String
Dim Starting As Integer
''Find the starting point
For I = 1 To UBound(data, 2) - 1
If data(I, 0) <> "" Then
Starting = I
Exit For
End If
Next
'''This primes the temp table
'' into #tempTable " & vbCrLf
If LCase(CStr(data(Starting, 0))) = "null" Then
Else
sSQL = "select '" & replace(CStr(data(Starting, 0)), "'", "''") & "' as '" & _
replace(CStr(data(0, 0)), "'", "''") & "'"
End If
For I = 1 To UBound(data, 2) - 1
If LCase(replace(CStr(data(Starting, I)), "'", "''")) = "null" Then
sSQL = sSQL & ", '' as '" & _
replace(CStr(data(0, I)), "'", "''") & "'"
Else
sSQL = sSQL & ", '" & replace(CStr(data(Starting, I)), "'", "''") & "' as '" & _
replace(CStr(data(0, I)), "'", "''") & "'"
End If
Next
sSQL = sSQL & ", getdate() as 'UpdateDate', suser_sname() as 'UpdatedBy' into #tempTable " & vbCrLf
' this adds all the data to the temp table
For I = Starting + 1 To UBound(data, 1)
If replace(CStr(data(I, 0)), "'", "''") = "" Then 'Checks to see ifs it has prop id, if not skip
Else
If LCase(replace(CStr(data(I, 0)), "'", "''")) = "null" Then 'checks to see if null if so add blank
sSQL = sSQL & "union Select ''"
Else
sSQL = sSQL & "union Select '" & replace(CStr(data(I, 0)), "'", "''") & "'" 'if not null add value
End If
For II = 1 To UBound(data, 2) - 1
If LCase(replace(CStr(data(I, II)), "'", "''")) = "null" Then
sSQL = sSQL & ", ''"
Else
sSQL = sSQL & ", '" & replace(CStr(data(I, II)), "'", "''") & "'"
End If
Next
sSQL = sSQL & ", getdate(), suser_sname() " & vbCrLf
End If
Next
'GuidanceInputForm.SellerConditioning.Text = sSQL
''UserForm1.Label1.Caption = Len(sSQLMerge)
'GuidanceInputForm.Show
''Add Merge code
sSQLMerge = "Merge CommercialSandbox..MasterDataTape as t" & vbCrLf & _
" Using #temptable as S on (replace(t.[Property ID], '-','') = replace(s.[Property ID], '-','') and replace(t.[Event ID], '-','') = replace(s.[Event ID], '-','')) " & vbCrLf & _
" When NOT MATCHED BY TARGET THEN INSERT([" & data(0, 0) & "]"
For I = 1 To UBound(data, 2) - 1
sSQLMerge = sSQLMerge & ", [" & data(0, I) & "]"
Next
sSQLMerge = sSQLMerge & ", UpdateDate, UpdatedBy"
sSQLMerge = sSQLMerge & ") VALUES (s.[" & data(0, 0) & "]"
For I = 1 To UBound(data, 2) - 1
sSQLMerge = sSQLMerge & ", s.[" & data(0, I) & "]"
Next
sSQLMerge = sSQLMerge & ", s.UpdateDate, s.UpdatedBy"
sSQLMerge = sSQLMerge & ") " & vbCrLf & _
" When MATCHED THEN UPDATE SET t.[" & data(0, 0) & "] = s.[" & data(0, 0) & "]"
For I = 1 To UBound(data, 2) - 1
sSQLMerge = sSQLMerge & ", t.[" & data(0, I) & "] = s.[" & data(0, I) & "]"
Next
sSQLMerge = sSQLMerge & ", t.UpdateDate = s.UpdateDate, t.UpdatedBy = s.UpdatedBy"
sSQLMerge = sSQLMerge & ";"
'GuidanceInputForm.SellerConditioning.Text = sSQLMerge
''UserForm1.Label1.Caption = Len(sSQLMerge)
'GuidanceInputForm.Show
sConnString = "Provider=sqloledb;Server=ERPT01LAX01US.prod.auction.local\EDWALT;Database=Commercialsandbox;Integrated Security = SSPI"
Set adoCN = CreateObject("ADODB.Connection")
adoCN.CommandTimeout = 0
adoCN.Open sConnString
adoCN.Execute sSQL
adoCN.Execute sSQLMerge
adoCN.Close

Resources