我需要能够遍历列名并将coloumn名称及其值放入变量中。我的代码看起来像这样。
SQL = "select column1, column2 from table1"
set rs = conn.execute(SQL)
For each fld in rs.fields
fld.name = rs(fld.name)
Next
rs.close
但这不起作用。如何循环列名并将其设置为变量而不必指定每个列名?
由于
答案 0 :(得分:7)
我认为你应该使用GetRows方法。返回一个二维数组。通过GetRows不需要列名。 考虑一下:
SQL = "select column1, column2 from table1"
set rs = conn.execute(SQL)
arrRecs = rs.GetRows
For row = 0 To UBound(arrRecs, 2) 'Rows
For col = 0 To UBound(arrRecs, 1) 'Columns
Response.Write rs.Fields(col).Name & " = " & arrRecs(col, row) & " "
Next
Response.Write "<br />"
Next
rs.close
答案 1 :(得分:0)
如果要存储字段名称,可以使用Dictionary并将每个字段名称作为键,然后将每列的值作为数组。
首先,翻译字典:
Set oData = Server.CreateObject("Scripting.Dictionary")
现在使用这两个循环填充数据:
For Each fld In rs.Fields
oData.Add fld.Name, Array()
Next
Do Until rs.EOF
For Each fld In rs.Fields
tempArray = oData(fld.Name)
ReDim Preserve tempArray(UBound(tempArray) + 1)
tempArray(UBound(tempArray)) = rs(fld.Name)
oData(fld.Name) = tempArray
Next
rs.MoveNext
Loop
最后,您可以使用以下代码显示所有列名称:
Response.Write("Column names:<br />")
For Each fld In oData.Keys
Response.Write(fld & " ")
Next
Response.Write("<br />")
或显示特定列的值:
Response.Write("Values for column named Id:<br />")
If oData.Exists("Id") Then
tempArray = oData("Id")
For x=0 To UBound(tempArray)
Response.Write(tempArray(x) & "<br />")
Next
Else
Response.Write("Such column does not exist")
End If
答案 2 :(得分:0)
使用上面的代码,并在会话中存储名称/值对,例如session(“table。”&amp; fieldname)= rs(fieldname)。我用它来存储用户,客户,供应商等信息。像缓存一样工作。您可以创建reloadCustomer(customerNumber)等子例程来重新加载。这样你就不会去DB了解基本信息。更改后更新...
字典对象:
set dic = server.createobject("scripting.dictionary")
dic.add "keyName1", "Michael"
dic.add "keyName2", "John"
dic.add "keyName3", "Steve"
dic.Item("keyName2") <-- gives you "John"