2009-07-27 75 views
1

我试图运行Excel中的一个SQL查询,我想:如何按“排序”列和“包含查询列名”?

1.为了通过我的专栏“工作站名称”
2.包括与查询

列名的查询结果现在它将返回没有列名称的所有列,并且最终用户不知道它是什么。

有人可以帮忙吗?我卡住了!下面是我当前的代码:

strQuery = "select pipelineflow.lciid lciid, ldate, volume, capacity, status, " & _ 
     "pipeline, station, stationname, drn, state, county, owneroperator, companycode, " & _ 
     "pointcode, pointtypeind, flowdirection, pointname, facilitytype, pointlocator, " & _ 
     "pidgridcode from pipelineflow, pipelineproperties " & _ 
     "where pipelineflow.lciid = pipelineproperties.lciid " & _ 
     "and pipelineflow.audit_active = 1 " & _ 
     "and pipelineproperties.audit_active =1 " & 
_ 
     "and pipelineflow.ldate " & dtInDate & _ 
     "and pipelineproperties.stationname = '" & Stationname & "' " 

回答

0

如需订购只是把

Order By stationname 

在查询结束。

可以使用通过列名重复:

rst(1).Name 

,其中第一个是你的记录,这个数字是列的索引。

1

对于问题的第1部分,在查询中添加ORDER BY子句。在这种情况下:通过站名命令

第2部分:不确定为什么列名未包含在查询中。您可以使用类似以下内容(纯粹是一个示例)来明确命名列:

select mycolumn as "MyCustomizedColumnName" from mytable 

允许您提供所选列名称。话虽如此,你不应该被要求为每一列都这样做,所以我怀疑你的情况还在发生其他事情。


我应该补充一点,存储过程(而不是动态SQL)会产生更好的运行时性能。

0

要对查询结果进行排序,请在查询结束处使用'ORDER BY'。您查询的最后一行是这样的

"and pipelineproperties.stationname = '" & Stationname & "' " & _ 
"ORDER BY pipelineproperties.stationname" 

列标题中查询数据返回,但不能自动写入到Excel工作表。下面的代码片段展示了如何遍历记录集的列标题并将它们写入活动单元格的行。

'第一'指您的记录集,根据需要更新名称。

If Not rst.EOF Then 
    For x = 0 To rst.Fields.Count - 1 
    With ActiveCell.Offset(0, lcount) 
     .Value = rst.Fields(x).Name 
    End With 
    Next 
End If 

确保您偏移从活动单元格写下来查询结果到工作表的时候,否则你的标题会被数据所覆盖。

Activecell.Offset(1,0).CopyFromRecordset rst