Groups | Blog | Home
all groups > sql server (microsoft) > may 2007 >

sql server (microsoft) : How to update selected rows in database? Please Help


Sand
5/12/2007 5:07:52 AM
Hi,



I have the following code.



Code Snippet
Private Sub BtnUpdate_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles BtnUpdate.Click

Dim a As DataTable = CType(DgvCnts.DataSource, DataTable)

Dim changedRows As New ArrayList ' retrieve changed rows

Dim changedIndex As New ArrayList ' retrieve the row index changed

For Each row As DataRow In a.Rows

If row.RowState <> DataRowState.Unchanged Then

'Get the index of the row that is changed

changedIndex.Add(a.Rows.IndexOf(row))

MsgBox(a.Rows.IndexOf(row))

changedRows.Add(row)

End If

Next

If changedRows.Count = 0 Then

Return

End If



Dim builder As New SqlCommandBuilder(adapter)

Dim rows() As DataRow = CType(changedRows.ToArray(GetType(DataRow)),
DataRow())

Dim counter As Integer = 0

Dim counter1 As Integer = 0

MsgBox(changedIndex.Count)

adapter.UpdateCommand = New SqlCommand("UPDATE table1 SET
(CT1,CT2,CT3,CT4) VALUES(@j1,@f1,@t1,@s1)", Main.new_connection)

For counter = 0 To changedIndex.Count - 1

''a.Rows(changedIndex.Item(counter)).SetParentRow(rows(counter))

a.Rows(changedIndex.Item(counter)).SetParentRow(rows(counter))

' adapter.UpdateCommand.Parameters.AddWithValue("@j1",
rows(counter).Item(0))

' adapter.UpdateCommand.Parameters.AddWithValue("@f1",
rows(counter).Item(1))

' adapter.UpdateCommand.Parameters.AddWithValue("@t1",
rows(counter).Item(2))

' adapter.UpdateCommand.Parameters.AddWithValue("@s1",
rows(counter).Item(3))

'adapter.Update(a)

Next



End Sub



The table i have does not have a primary key. When i click on update,
the row that was modified needs to be updated in the database too.
However, currently the update is reflected only on the datagrid but
not on the actual database. To my knowledge, to use the Update
function the table requires a primary key. How do I make the update on
the actual database (no primary key for table)? Hope someone can help
me out here.



Thanks!
Ed Murphy
5/12/2007 10:06:23 AM
[quoted text, click to view]

You're mixing syntaxes. To add a new row:

INSERT INTO table1 (CT1,CT2,CT3,CT4) VALUES (@j1,@f1,@t1,@s1)

To change existing rows:

UPDATE table1 SET CT1=@j1, CT2=@f1, CT3=@t1, CT4=@s1

[quoted text, click to view]

Then you should either add one, or define a set of one or more
existing columns as being one. The specific details depend on
the concepts underlying this table's data.

[quoted text, click to view]

An UPDATE statement affects any row matching the WHERE clause (if
there is no WHERE clause, then it affects every row).

The most straightforward way to affect just one row of a table is
indeed to use its primary key in the WHERE clause (assuming that the
table has a primary key, and also that it has a row whose primary key
AddThis Social Bookmark Button