How to retrieve XML data from SQL Server 2005?

2020-07-16 13:54发布

问题:

My script:

Dim myStream, myConnection, myCommand
Set myStream = CreateObject("ADODB.Stream")
Set myConnection = CreateObject("ADODB.Connection")
Set myCommand = CreateObject("ADODB.Command")
'
myConnection.Open "Provider=SQLOLEDB;Integrated Security=SSPI;" & _
"Persist Security Info=False;Initial Catalog=DSIPAR;Data Source=.\DSIDATA"

myCommand.ActiveConnection = myConnection

myCommand.CommandText = "SELECT itemsgt, item FROM NIFItem"

myStream.Open

myCommand.Properties("Output Stream") = myStream
myCommand.Execute , , adExecuteStream

myStream.Position = 0
myStream.Charset = "ISO-8859-1"

Dim strxml
strxml = myStream.ReadText
MsgBox (strxml)

I can run the script and I can see the query execute on my SQL server instance, but nothing is ever returned to the output stream.

回答1:

To retrieve the results into a stream, the query needs to include "FOR XML AUTO". Also change the text adExecuteStream to the constant value 1024.

Full Code:

Dim myStream, myConnection, myCommand
Set myStream = CreateObject("ADODB.Stream")
Set myConnection = CreateObject("ADODB.Connection")
Set myCommand = CreateObject("ADODB.Command")
myConnection.Open "Provider=SQLOLEDB;Integrated Security=SSPI;" & _
"Persist Security Info=False;Initial Catalog=DSIPAR;Data Source=.\DSIDATA"
myCommand.ActiveConnection=myConnection

myCommand.CommandText="SELECT itemsgt,item FROM NIFItem FOR XML AUTO"

myStream.Open
myCommand.Properties("Output Stream") = myStream
myCommand.Properties("xml root") = "root"

myCommand.Execute ,,1024 'instead of adExecuteStream
myStream.Position=0
myStream.Charset="ISO-8859-1"
Dim strxml
strxml = myStream.ReadText
MsgBox (strxml)

If you don't need a stream and instead want to read the values of itemsgt and item, try this instead:

Dim myStream, myConnection, myCommand, adoRec
Set myStream = CreateObject("ADODB.Stream")
Set myConnection = CreateObject("ADODB.Connection")
Set myCommand = CreateObject("ADODB.Command")
myConnection.Open "Provider=SQLOLEDB;Integrated Security=SSPI;" & _
"Persist Security Info=False;Initial Catalog=DSIPAR;Data Source=.\DSIDATA"
myCommand.ActiveConnection=myConnection
myCommand.CommandText="SELECT itemsgt,item FROM NIFItem"
SET adoRec = myCommand.Execute()
'Get the first results
If Not adoRec.EOF then
  MsgBox "itemsgt = "  & adoRec(0) & vbcrlf & "item="  &  adoRec(1)
End If

'Iterate through the results
While Not adoRec.EOF
  itemsgt = adoRec(0)
  item = adoRec(1)
  'MsgBox "itemsgt = " & itemsgt & vbcrlf & "item="  & item
  adoRec.MoveNext
Wend


标签: vbscript