Thursday, May 19, 2016

Retrieving data from SQL Server using RecordSet object in VBScript

Option Explicit

Dim Conn ' Connection Variable
Dim rs ' Recordset Variable
Dim sqlQuery
Dim serverName
Dim field


'Declare the SQL statement that will query the database
sqlQuery = "SELECT UserName FROM dbo.UserList WHERE ID = '9'"


'Create an instance of the ADO connection and recordset objects

Set Conn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")


'Open the connection to the database
Conn.Open "DSN=getUser;UID=user1;PWD=password;Database=dbUserList"


'Open the recordset object executing the SQL statement and return records 
rs.Open sqlQuery,Conn


'Check if any record exist in table 
If rs.EOF Then 
wscript.echo "No Record Found"
wscript.quite
Else 

Do While NOT rs.Eof   
field = rs("UserName")
if field <> "" then
  wscript.echo field
end if
rs.MoveNext     
Loop

End If


'Close Connection and Recordset
rs.Close
Set rs=nothing
Conn.Close
Set Conn=nothing

No comments:

Post a Comment

Your feedback is always appreciated. I will try to reply to your queries as soon as time allows.Please don't spam,spam comments will be deleted upon reviews.