[英]Looping through Records to get total
我有一个网页,希望显示使用Visual Basic花费的总休假时间。 所有日期都存储在SQL数据库中。
我希望它能在tblworkhours中获得所有员工登录计算机的记录,工作代码为2,用于休假,然后我将计算休假总时间。
我将其设置为对表中的所有记录进行计数(工作正常)。 然后,我计算出该记录中的休息时间(工作正常)。 我的问题-从该记录中获取信息后,我想转到下一个记录以减少其工作时间,然后再获取下一个,依此类推,直到获得该员工的总工作时间。 我不知道如何获取下一条记录以及下一条记录,依此类推,直到到达记录末尾为止。
示例–我的select count语句显示我有2条记录,其中雇员是登录人员,工作代码是休假(2)。
第一条记录-开始日期6/13/15-结束日期6/15/15-因此,我计算了3天或24小时
第二条记录-开始日期6/20/15-结束日期6/20/15-1天或8小时
我的代码计算了多少条记录-2。“直到”语句可以正常工作-它计算1和2,但是将第一条记录计算为2x。 而不是总计32小时(第一记录小时加第二记录小时),我得到48小时(第一记录小时2倍)。
仅供参考-我在加班上没问题。 我的代码必须计算小时数,因为表格中只有日期和时间。 在此先感谢您的帮助!
这是我的代码-我保留了运行良好的部分:
Dim sqlConnection As New SqlConnection("Data Source=WillSQL\ict2;Initial Catalog=TimeSQL;Integrated Security=SSPI")
Dim commandvct As New SqlCommand
Dim returnvct As Object
commandvct.CommandText = "Select count(workhoursid) from tblworkhours where Employee = " & rve & " and workcode = 2"
'workcode 2 is vacation. Count works fine.
commandvct.CommandType = CommandType.Text
commandvct.Connection = sqlConnection
sqlConnection.Open()
returnvct = commandvct.ExecuteScalar
sqlConnection.Close()
Do Until returnvct = 0
returnvct = returnvct - 1
' Deleted code that gets how many hours - this code works fine.
Loop
让我展示一下您可以使用Sql语言做什么。 在此示例中,我将仅使用SQL汇总休假时间
create table A (name varchar(100), bdate datetime, edate datetime)
-- I set dates to string, it will convert to rounded dates.
insert into a values ('AAA', '02/05/2015', '02/05/2015') -- 1 day / 8 hrs
insert into a values ('AAA', '06/05/2015', '06/09/2015') -- 5 days / 40 hrs
insert into a values ('BBB', '02/05/2014', '02/05/2014') -- 1 day / 8 hrs
insert into a values ('BBB', '06/05/2014', '06/07/2014') -- 3 days / 24 hrs
-- But when taking dates out, you need to cut off hours, minutes, etc - use CAST
select name, SUM(case
when CAST(bdate as date) = CAST(edate as date) Then 8
else (datediff(day, CAST(bdate as date), CAST(edate as date)) + 1) * 8 -- +1 to make date inclusive
end) as vacaHours
from a
where name = 'AAA' -- comment this and all people will return
group by name
仅AAA
输出
name vacaHours AAA 48
全部输出
name vacaHours AAA 48 BBB 32
现在,您可以打开DataReader并将值读入程序
' They said, sql injection words... this is what you do - notice alias for count
cmd.CommandText = "Select count(workhoursid) as count from tblworkhours where Employee = @1 and workcode = @2"
cmd.Parameters.AddWithValue("@1", rve)
cmd.Parameters.AddWithValue("@2", 2)
' some code here
cmd.CommandType = CommandType.Text
' some code here
Using reader As IDataReader = cmd.ExecuteReader()
' do something with each record
While reader.Read()
myvar = Convert.ToInt32(reader("count"))
End While
End Using
根据此代码中的SQL查询,您只有一条记录。 没有第二条记录。
该查询将返回一条记录,其中包含符合条件的所有记录的计数 。 并且您正确使用了ExecuteScalar
方法来获取该值。
除了每次都从返回的整数中减去一个以外,尚不清楚最后要循环执行什么操作。 您当然不会遍历任何数据记录。
如果需要所有记录,则选择所有记录。
SELECT * FROM tblworkhours where Employee = " & rve & " and workcode = 2
然后使用它返回一个数据读取器并遍历那里的记录。
已经提到您应该使用参数。 没错,但可能会分散您的主要问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.