-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathsource.vb
More file actions
92 lines (72 loc) · 3.14 KB
/
Copy pathsource.vb
File metadata and controls
92 lines (72 loc) · 3.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
Option Explicit On
Option Strict On
Imports System.Data
Imports System.Data.SqlClient
Module Class1
Sub Main()
Dim connectionString As String = _
GetConnectionString()
MergeIdentityColumns(connectionString)
Console.ReadLine()
End Sub
' <Snippet1>
Private Sub MergeIdentityColumns(ByVal connectionString As String)
Using connection As SqlConnection = New SqlConnection( _
connectionString)
' Create the DataAdapter
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"SELECT ShipperID, CompanyName FROM dbo.Shippers", connection)
' Add the InsertCommand to retrieve new identity value.
adapter.InsertCommand = New SqlCommand( _
"INSERT INTO dbo.Shippers (CompanyName) " & _
"VALUES (@CompanyName); " & _
"SELECT ShipperID, CompanyName FROM dbo.Shippers " & _
"WHERE ShipperID = SCOPE_IDENTITY();", _
connection)
' Set AcceptChangesDuringUpdate to false.
adapter.AcceptChangesDuringUpdate = False
' Add the parameter for the inserted value.
adapter.InsertCommand.Parameters.Add( _
New SqlParameter("@CompanyName", SqlDbType.NVarChar, 40, _
"CompanyName"))
adapter.InsertCommand.UpdatedRowSource = _
UpdateRowSource.FirstReturnedRecord
' MissingSchemaAction adds any missing schema to
' the DataTable, including auto increment columns
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
' Fill a DataTable.
Dim shipper As New DataTable
adapter.Fill(shipper)
' Add a new shipper row.
Dim newRow As DataRow = shipper.NewRow()
newRow("CompanyName") = "New Shipper"
shipper.Rows.Add(newRow)
' Add changed rows to a new DataTable. This
' DataTable will be used to update the data source.
Dim dataChanges As DataTable = shipper.GetChanges()
' Update the data source with the modified records.
adapter.Update(dataChanges)
Console.WriteLine("Rows before merge.")
Dim rowBefore As DataRow
For Each rowBefore In shipper.Rows
Console.WriteLine("{0}: {1}", rowBefore(0), rowBefore(1))
Next
' Merge the two DataTables to get new values.
shipper.Merge(dataChanges)
' Commit the changes.
shipper.AcceptChanges()
Console.WriteLine("Rows after merge.")
Dim rowAfter As DataRow
For Each rowAfter In shipper.Rows
Console.WriteLine("{0}: {1}", rowAfter(0), rowAfter(1))
Next
End Using
End Sub
' </Snippet1>
Private Function GetConnectionString() As String
' To avoid storing the connection string in your code,
' you can retrieve it from a configuration file.
Return "Data Source=(local);Initial Catalog=Northwind;" _
& "Integrated Security=true;"
End Function
End Module