VBA를 사용하여 SQL 테이블에만 새 레코드 삽입
아래 코드의 엑셀 워크북을 가지고 있습니다.
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
이렇게 하면 데이터베이스에 대한 연결이 열리고 지정된 열에서 값을 입력합니다.
기본 키는 데이터베이스의 증분 키입니다.문제는 모든 값을 복사한다는 것입니다.
엑셀 시트에 새로운 데이터 행을 추가하고 기존에 없는 행만 삽입하고 싶습니다.
여러가지 방법('병합', '존재하면', '존재하지 않으면' 등)을 시도해 보았지만 제대로 된 방법이 없습니다.
해결책은 VBA를 통해서 이루어져야 합니다.SSMS를 사용하여 링크를 설정하는 것은 옵션이 아닙니다.
임시 테이블을 사용한 후 병합을 수행하는 절차를 시작하는 것이 가능할 수도 있다는 것은 이해하지만, 마지막 수단으로 검토하고자 합니다.아직 읽지 않았지만(MS SQL 성경책을 통과하는 중) 필요하지 않기를 바랍니다.
--- @Kannan의 답변에서 업데이트 ---
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 & "')"
키워드 'THEN' 근처의 잘못된 구문' 오류를 반환합니다.
SQL 쿼리가 올바르지 않습니다. 없습니다.THEN
SQL로IF
.
또한 존재하는 경우에는 아무것도 할 필요가 없으므로 존재하지 않는 경우에만 사용할 수 있습니다.
"IF NOT EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" & sFirstName & "' and LastName = '" & sLastName & "') " & _
"INSERT INTO dbo.Customers (FirstName, LastName) " & _
"VALUES ('" & sFirstName & "', '" & sLastName & "')"
이 정도면 충분합니다.
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
참조 추가: Microsoft ActiveX Data Objects 2.8 라이브러리
참고로, 제 시트는 이렇게 생겼네요.
sql 쿼리는 다음과 같이 사용할 수 있습니다.
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 & "')"
Excel과 C#의 구문에 대해 잘 모르므로 이 쿼리와 유사하게 수정할 수 있습니다.
언급URL : https://stackoverflow.com/questions/39293669/insert-new-records-only-into-sql-table-using-vba
'code' 카테고리의 다른 글
잘못된 범위: publish_actions, manage_pages, publish_pages, user_managed_groups, user_posts, user_phots (0) | 2023.09.20 |
---|---|
메모장++:파일 로드 시 Language를 Xml로 자동 설정하는 방법 (0) | 2023.09.20 |
Pandas Dataframe에서 빈 항목 또는 NaN 항목 찾기 (0) | 2023.09.20 |
Oracle: 여러 열에 대한 빠른 NOT IN (0) | 2023.09.20 |
판다 콘캣은 nan 값을 만들어냅니다. (0) | 2023.09.20 |