我真的很累。我有这个查询它非常适合我的Sql服务器数据库但是当我把它与我的MS Access数据库放在一起时我有一个错误(索引(零基数)必须大于或等于零并且小于参数列表的大小)。 Sql server查询:
Dim sql As String = String.Format(" SELECT TOP {0} ID1,Team1,Team2,Team3 FROM (SELECT ROW_NUMBER() OVER(ORDER BY newid() ASC) AS F1, ID1, Team1, Team2 FROM Table1 ) as t1 INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY newid() ASC) AS F1,Team3 FROM Table2 ) as t2 on t1.f1 = t2.f1", rows)
MS Access查询:
Dim sql As String = String.Format(" SELECT TOP (0) ID1,Team1,Team2,Team3 FROM (SELECT ROW_NUMBER() OVER(ORDER BY {" & Guid.NewGuid().ToString & "} ASC) AS F1,ID1,Team1,Team2 from Table1) as t1 INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY {" & Guid.NewGuid().ToString & "} ASC) AS F1, Team3 FROM Table2 ) as t2 on t1.f1 = t2.f1 ", rows)
我在Form1中的代码加载:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Conn_Randomize()
InfoCommand = New OleDbCommand("SELECT * FROM Table1 ORDER BY Team2", Conn_Randomize)
InfoAdapter = New OleDbDataAdapter()
InfoAdapter.SelectCommand = InfoCommand
InfoTable = New DataTable()
InfoAdapter.Fill(InfoTable)
DataGridView1.DataSource = InfoTable
End Sub
我希望在DataGridView2中使用NumericupDown1和2显示输入行数和列数的代码并随机化
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Conn_Randomize()
Dim rows As Integer
If Not Integer.TryParse(NumericUpDown1.Value, rows) Then
MsgBox("NUMBER NOT AVAILABLE", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Error")
NumericUpDown1.Value = ""
NumericUpDown1.Focus()
Exit Sub
End If
If NumericUpDown2.Value = 2 Then
Dim sql As String = String.Format("SELECT Top {0} ID1, Team1, Team2 FROM Table1 ORDER BY RND(-(100000*ID1)*Time())", rows)
InfoCommand = New OleDbCommand(sql, Conn_Randomize)
InfoAdapter = New OleDbDataAdapter()
InfoAdapter.SelectCommand = InfoCommand
InfoTable = New DataTable()
InfoAdapter.Fill(InfoTable)
DataGridView2.DataSource = InfoTable
End If
If NumericUpDown2.Value = 3 Then
Dim sql As String = String.Format(" SELECT TOP {0} ID1,Team1,Team2,Team3 FROM (SELECT ROW_NUMBER() OVER(ORDER BY {" & Guid.NewGuid().ToString & "} ASC) AS F1,ID1,Team1,Team2 from Table1) as t1 INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY {" & Guid.NewGuid().ToString & "} ASC) AS F1, Team3 FROM Table2 ) as t2 on t1.f1 = t2.f1 ", rows)
InfoCommand = New OleDbCommand(sql, Conn_Randomize)
InfoAdapter = New OleDbDataAdapter()
InfoAdapter.SelectCommand = InfoCommand
InfoTable = New DataTable()
InfoAdapter.Fill(InfoTable)
DataGridView2.DataSource = InfoTable
End If
End Sub
答案 0 :(得分:2)
在执行第二个代码段后,您是否真正了解了sql
包含的内容?它有意义吗?
第一个代码片段使用的是newid
,这是一个T-SQL函数,这意味着数据库将为每一行生成一个新的uniqueidentifier
并使用它们对数据进行排序。第二个代码片段怎么能做同等的事情呢?它只在VB代码中调用NewGuid
一次,并将结果连接到SQL代码中。您很幸运,这甚至是有效的语法,但结果并不是每条记录都有不同的值要排序。
您需要数据库为每个可用作排序键的记录生成值,并且在Access SQL中生成随机数的方法是Rnd
。我以为你那天前已经在使用了。
另外,虽然我还没有检查过,但我也不确定Access中是否支持ROW_NUMBER
。很久以前它就没有被添加到SQL Server中。