我有以下代码:
Imports System.Data
Imports System.Data.OleDb
Partial Class Dummy
Inherits System.Web.UI.Page
Dim r As OleDbDataReader
Dim con As OleDb.OleDbConnection
Dim cmd As OleDbCommand
Dim cmd1 As OleDbCommand
Dim prev_ob As New List(Of Int64)
Dim cur_ob As Integer
Dim i As Integer = 0
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New OleDb.OleDbConnection("provider=SQLOLEDB;data source=PC;initial catalog=DB1;integrated security=SSPI")
cmd = New OleDbCommand("select single_column from table1 where date_reqd=(SELECT CONVERT(VARCHAR(10),DATEADD(DD, DATEDIFF(DD, 0, GETDATE()), -1),120))", con)
con.Open()
r = cmd.ExecuteReader
While r.Read
prev_ob.Add(Val(r.Item(0)))
End While
cmd = New OleDbCommand("select column1, column2, date_reqd from table1 where date_reqd=(select CONVERT(varchar(10), GETDATE(),120))", con)
r = cmd.ExecuteReader
While r.Read
For i As Integer = 0 To prev_ob.Count - 1
cur_ob = Val(prev_ob(i)) + Val(r.Item(0))
cmd1 = New OleDbCommand("update table1 set column4='" & cur_ob & "' where column2='" & r.Item(1) & "' and date_reqd='" & r.Item(2) & "'", con)
cmd1.ExecuteNonQuery()
i += 1
Exit For
Next
End While
con.Close()
End Sub
End Class
我面临的问题是更新仅针对许多值中的第一个正确发生。计算所有其他值,因此在我的表中更新不正确。我几乎可以肯定,循环是导致问题的原因,但一直无法找到解决方法。请帮我纠正。
答案 0 :(得分:1)
看起来这应该是一个UPDATE语句。不幸的是,在没有看到实际的表结构的情况下告诉它是很棘手的。首先,写一个这样的select语句(我希望date_reqd实际上也是一个datetime列):
SELECT
*
FROM
table1 t1a
inner join
table1 t1b
on
t1a.date_reqd = DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),-1) and
t1b.date_reqd = DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),0) and
/* You need other conditions here if there are multiple rows for the same dates
- I'm guessing there are since you're trying to write a loop */
使用此查询后,请删除前两行(SELECT *
),并将其替换为:
UPDATE
t1b
SET
column4 = t1a.single_column + t1b.column1
你应该完成。
答案 1 :(得分:0)
我自己拿到了! :)我需要做的就是:
Dim i as Integer=0
While r.Read
cur_ob = Val(prev_ob(i)) + Val(r.Item(0))
cmd1 = New OleDbCommand("update table1 set column4='" & cur_ob & "' where column2='" & r.Item(1) & "' and date_reqd='" & r.Item(2) & "'", con)
cmd1.ExecuteNonQuery()
cur_ob = 0
i += 1
End While
它有效!感谢您的回答/评论和@Damien_The_Unbeliever,我更改了我的主要查询以包含ORDER BY
子句。谢谢你的提示! :)