Connecting to sql server 2008 using vb - vb.net

Function DBConnect()
Dim vConnString, wfConnection, objConn
set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open Application("DB_CONNECT")
set DBConnect = objConn
exit function
Response.Write("connected to Server 2008")
End Function
Function GetValue()
Dim objCmd, objRS
Set objCMD = Server.CreateObject("ADODB.Command")
Set objRs = Server.CreateObject("ADODB.Recordset")
With (objCMD)
.ActiveConnection = DBConnect()
.CommandType = adCmdStoredProc
.CommandText = "select * from Acc.dbo.table"
set ObjRS = .Execute()
End With
if err.number = 0 then
if not objRs.EOF then
arrData = objRs.GetRows
vDesc = arrData(5,0)
else
vDesc = vValue
end if
GetDescFromCode = True
end if
Response is Coming as
connected to Server 2008
While debuging, i got that its not going inside objRs.EOF if loop...any idea whats wrong

In DBConnect, check the status of objConn to make sure it's really being opened.
In DBConnect, you have exit function before response.write.
In GetValue, check value of err.number.

Related

Is it possible to pass a parameter from MS Access to a SQL Server stored procedure and display the output in a datasheet form?

Users in MS Access enter values in a field that is passed as a parameter to a stored procedure in a SQL Server database. The stored procedure will return a result set with two columns. I would like to display that result set in a datasheet form. The code below almost does that, but will only display the final row of the result set. I confirmed that the stored procedure is being passed to the db correctly and that the test values I'm using should return 4 rows. The code in comments are a few of the many things that I have tried that didn't work.
Private Sub btnBulkLink_Click()
Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset
With cmd
.CommandType = adCmdStoredProc
.ActiveConnection = "Driver=SQL Server Native Client 11.0;Server=xxxxxxxxxxxxxxxxx;Database=xxxxx;Trusted_Connection=Yes"
.CommandText = "dbo.usp_FindResolutionsLinkedToServices"
.CommandTimeout = 180
.NamedParameters = True
End With
cmd.Parameters.Append cmd.CreateParameter("#PprsRefINP", adLongVarChar, adParamInput, Len(txtBulkLink.Value), txtBulkLink.Value)
Set rst = cmd.Execute
DoCmd.OpenForm FormName:="ServiceResolutionLink", View:=acFormDS, DataMode:=acFormReadOnly, WindowMode:=acHidden
' Set Forms!ServiceResolutionLink.Recordset = rst
With rst
Do While Not .EOF
Forms("ServiceResolutionLink").txtPprsRef = rst!PprsRef
Forms("ServiceResolutionLink").txtSubmissionId = rst!SubmissionId
.MoveNext
Loop
End With
' Forms("ServiceResolutionLink").txtPprsRef = rst!PprsRef
' Forms("ServiceResolutionLink").txtSubmissionId = rst!SubmissionId
' Forms("ServiceResolutionLink").Visible = True
DoCmd.OpenForm FormName:="ServiceResolutionLink", View:=acFormDS
rst.Close
End Sub
Ok, we assume you setup a pass-though query. (and it set with returns records = true).
And if your datasheet is a REAL sub form (setup as datasheet - not a table).
Then this code will work:
Private Sub Command2_Click()
With CurrentDb.QueryDefs("qryPassR")
.SQL = "exec dbo.GetHotels2 #City = '" & "Banff" & "'"
End With
Me.MyDataSheet.Form.RecordSource = "qryPassR"
End Sub
And if you are using a real datasheet (form that does not exist), then you can have the form set to
Query.PassR
The trick (or challenge) then becomes to have the form NOT load until such time you setup the query with the correct stored procedure call.
I was in the midst of testing suggestions from others when my boss figured this out. Here is our final code:
Private Sub Form_Load()
Dim rst As New ADODB.Recordset
Dim cmd As New ADODB.Command
Dim strPPRSRef As String
Dim cn As New ADODB.Connection
With cn
.Provider = "sqloledb"
cn.Properties("Data Source").Value = "[server]"
cn.Properties("Initial Catalog").Value = "[db]"
cn.CursorLocation = adUseClient
' Windows authentication.
cn.Properties("Integrated Security").Value = "SSPI"
' .CursorLocation = adUseClient
End With
cn.Open
With cmd
.CommandType = adCmdStoredProc
.ActiveConnection = cn
.CommandText = "dbo.usp_FindResolutionsLinkedToServices"
.CommandTimeout = 180
.NamedParameters = True
End With
strPPRSRef = Forms("Resolution_Tracker").txtBulkLink.Value
cmd.Parameters.Append cmd.CreateParameter("#PprsRefINP", adLongVarChar, adParamInput, Len(strPPRSRef), strPPRSRef)
With rst
.CursorType = adOpenStatic
.CursorLocation = adUseClient
End With
Set rst = cmd.Execute
Set Me.Recordset = rst
rst.Close
Set rst = Nothing
cn.Close
Set cn = Nothing
End Sub

Access FE SQL BE ODBC Call Failed and Object Invalid or No Longer Set with Stored Procedure

I'm using Access 13 frontend with a SQL 2012 backend. I call a stored procedure from Access using the below code and receive the message 'ODBC Call Failed'. After that I then receive the message 'Object Invalid or No Longer Set' The strange thing is, it returns the correct data from SQL server then produces the error. When I click ok, I can continue to call the SP without any further errors until Access is closed\re-opened. Below is my VBA code (in debug it produces the error on: Set Me!lstItems.Recordset = rs
Also, if connected on the network, it works fine, if connecting via a VPN, the error occurs. We have checked everything we can on the VPN to no avail - any ideas?
Private Sub cmdSearch_Click()
On Error GoTo cmdSearch_Click_Error
If IsNull(Me.txtSearch) Then
MsgBox "Please enter a value to search", vbInformation
Else
DoCmd.Hourglass True
Set CN = New ADODB.Connection
CN.ConnectionString = "DRIVER=SQL Server;SERVER=XXXXXXXXXXX;Database=XXXXXXXXXXXXXX;Trusted_Connection=YES;"
CN.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = CN
.CommandText = "dbo.PVXSearch"
.CommandType = adCmdStoredProc
Set prm = .CreateParameter("#Search", adVarWChar, adParamInput, 50)
prm.Value = Me.txtSearch
.Parameters.Append prm
cmd.Execute
End With
Set rs = New ADODB.Recordset
With rs
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockReadOnly
.Open cmd
End With
Set Me!lstItems.Recordset = rs
Me.lstItems.Requery
Set prm = Nothing
Set cmd = Nothing
Set rs = Nothing
DoCmd.Hourglass False
End If
On Error GoTo 0
Exit Sub
cmdSearch_Click_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure cmdSearch_Click of VBA Document Form_frmWebOrder - Please take a screenshot and email XXXXXXXXXXXXXXXXXX"
End Sub

Excel VBA stored procedure with parameters not working?

I am struggling bit here with a stored procedure with parameters in VBA. The code below without parameters working fine but with parameters not working.
My code:
Sub CopyDataFromDatabase()
Dim Conn As ADODB.Connection
Dim Rs As ADODB.Recordset
Dim Fields As ADODB.Field
Dim Cmd As ADODB.Command
Set Conn = New ADODB.Connection
Set Cmd = New ADODB.Command
Set Rs = New ADODB.Recordset
Conn.Open "My connection string here--------"
Cmd.CommandType = adCmdStoredProc
Cmd.Parameters.Append Cmd.CreateParameter("#Division", adVarChar, adParamInput, 40)
Cmd.Parameters("#Division").Value = "South"
Cmd.Parameters.Append Cmd.CreateParameter("#Area", adVarChar, adParamInput, 40)
Cmd.Parameters("#Area").Value = "IT"
Cmd.CommandText = "My SP here------"
Set Rs = Cmd.Execute
On Error GoTo CloseRecordset
Worksheets.Add
For Each Fields In Rs.Fields
ActiveCell.Value = Fields.Name
ActiveCell.Font.Bold = True
ActiveCell.Font.Underline = True
ActiveCell.HorizontalAlignment = xlCenter
ActiveCell.Interior.Color = RGB(0, 128, 255)
ActiveCell.Font.Color = RGB(255, 255, 255)
ActiveCell.Offset(0, 1).Select
Next Fields
Range("A1").Select
Range("A2").CopyFromRecordset Rs
CloseRecordset:
Rs.Close
Set Rs = Nothing
Set Cmd = Nothing
CloseConnection:
Conn.Close
Set Conn = Nothing
End Sub
When I run, its not giving any error, just showing like executing but no result
Can anybody suggest where I am doing wrong? Thanks
I have successfully declared a variant array and populated the parameters (in order!) into that array, then passed to the array into the execute method to execute a stored procedure.
Assuming your stored proc expects 'Division' then 'Area', something like this may do the trick:
Sub CopyDataFromDatabase()
Dim Conn As ADODB.Connection
Dim Rs As ADODB.Recordset
Dim Fields As ADODB.Field
Dim Cmd As ADODB.Command
'New variable
Dim v_Params(1 To 2) As Variant 'assuming you have 2 parameters
Set Conn = New ADODB.Connection
Set Cmd = New ADODB.Command
Set Rs = New ADODB.Recordset
Conn.Open "My connection string here--------"
v_Params(1) = "South"
v_Params(2) = "IT"
With Cmd
.ActiveConnection = Conn
.CommandType = adCmdStoredProc
.CommandText = "My SP here------"
.CommandTimeout = 0
Set rs = .Execute(, v_Params)
End With
See if that works, as I am currently using this method successfully. I didn't see the need to modify the rest of your subroutine.
I used the With Cmd and End With to avoid fully qualifying the reference each time.
Updated
The issue, found by the author of the question, was that the SP was timing out when parameters were passed into it. The resolution was to set the CommandTimeout property to 0.

ASP SQL Server Connection

<%
DIM objConn
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.ConnectionString = "Data Source=123.123.12.123,1234;Database=DatabaseName;User Id=Usernm;Password=abcd1234;"
objConn.Open
DIM mySQL
mySQL = "SELECT * FROM [Users] WHERE [User ID]='1'"
DIM objRS
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.open(mySQL, objConn)
Response.Write objRS("FullName")
objRS.Close
Set objRS = Nothing
objConn.Close
Set objConn = Nothing
%>
I want to connect to a SQL Server Database, read the data and close the connection. I have studied the examples and came up with this. But its not working. Please guide me. Where am I going wrong?
Some answers have suggested wrapping logic into functions there is no need for this.
It's just a lot of fluff that isn't needed, just use the ADODB.Command object. There are hundreds of ways to approach this but a method I have found to work time and again is let the ADODB.Command object do the work then return your results into an Array using .GetRows() method of the ADODB.Recordset object.
That way you can close off both the ADODB.Recordset and ADODB.Command objects quickly and work just with the Array.
Dim conn, cmd, rs, sql, data, search
'Assume value to query comes from a Request Collection.
search = Request("myvalue") & ""
conn = "Data Source=123.123.12.123,1234;Database=DatabaseName;User Id=Usernm;Password=abcd1234;"
sql = "select from mytable where this = ?"
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
'No need to handle connection let ADODB.Command create and destory it.
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = sql
.Parameters.Append(.CreateParameter("#myparam", adVarWChar, adParamInput, 50))
.Parameters("#myparam").Value = search
Set rs = .Execute()
If Not rs.EOF Then data = rs.GetRows()
Call rs.Close()
Set rs = Nothing
End with
Set cmd = Nothing
'ADODB.Connection is closed when ADODB.Command is destroyed.
If IsArray(data) Then
rows = UBound(data, 2)
For row = 0 To rows
'Return first column of the current row
Call Response.Write("First Column of Row " & row & " is '" & data(0, row) & "'<br />"
Next
Else
Call Response.Write("No records")
End If
Dim rs, dbConn
Function OpenDB()
Set dbConn = Server.CreateObject("ADODB.Connection")
dbConn.ConnectionTimeout = 300
dbConn.CommandTimeout = 300
dbConn.Open "Data Source=123.123.12.123,1234;Database=DatabaseName;User Id=Usernm;Password=abcd1234;"
End Function
Function CloseDB()
Set rs = Nothing
if ucase(TypeName(dbConn)) = "CONNECTION" then
dbConn.Close
Set dbConn = Nothing
end if
End Function
Function OpenRecordSet(recset, tablename)
Call OpenDB()
Set recset = Server.CreateObject("ADODB.Recordset")
recset.Open tablename, dbConn, 0, 1
End Function
Function CloseRecordSet(recset)
Set recset = Nothing
Call CloseDB()
End Function
Then use
<%
Call OpenDB()
sql = "select from mytable where this = 'that'"
Set rs = dbConn.Execute(sql)
if not rs.EOF then
' do your stuff!
end if
Call CloseDB()
%>
http://www.shiningstar.net/articles/articles/database/datafunctions.asp?ID=AW

The instruction at "0x7c910a19" referenced memory at "oxffffffff". The memory could not be "read"

The instruction at "0x7c910a19" referenced memory at "oxffffffff". The memory could not be "read"
I have a small issue, I receive the error above before the .vbs terminates. I don't know why this error is thrown. Below is the process of the .vbs file:
Call ImportTransactions()
Call UpdateTransactions()
Function ImportTransactions()
Dim objConnection, objCommand, objRecordset, strOracle
Dim strSQL, objRecordsetInsert
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "DSN=*****;UID=*****;PWD==*****;"
Set objCommand = CreateObject("ADODB.Command")
Set objRecordset = CreateObject("ADODB.Recordset")
strOracle = "SELECT query here from Oracle database"
objCommand.CommandText = strOracle
objCommand.CommandType = 1
objCommand.CommandTimeout = 0
Set objCommand.ActiveConnection = objConnection
objRecordset.cursorType = 0
objRecordset.cursorlocation = 3
objRecordset.Open objCommand, , 1, 3
If objRecordset.EOF = False Then
Do Until objRecordset.EOF = True
strSQL = "INSERT query here into SQL database"
strSQL = Query(strSQL)
Call RunSQL(strSQL, objRecordsetInsert, False, conTimeOut, conServer, conDatabase, conUsername, conPassword)
objRecordset.MoveNext
Loop
End If
objRecordset.Close()
Set objRecordset = Nothing
Set objRecordsetInsert = Nothing
End Function
Function UpdateTransactions()
Dim strSQLUpdateVAT, strSQLUpdateCodes
Dim objRecordsetVAT, objRecordsetUpdateCodes
strSQLUpdateVAT = "UPDATE query here SET [value:costing output] = ([value:costing output] * -1)"
Call RunSQL(strSQLUpdateVAT, objRecordsetVAT, False, conTimeOut, conServer, conDatabase, conUsername, conPassword)
strSQLUpdateCodes = "UPDATE query here SET [value:costing output] = ([value:costing output] * -1) different WHERE clause"
Call RunSQL(strSQLUpdateCodes, objRecordsetUpdateCodes, False, conTimeOut, conServer, conDatabase, conUsername, conPassword)
Set objRecordsetVAT = Nothing
Set objRecordsetUpdateCodes = Nothing
End Function
UDPATE: If I exit the function after I open the connection (see below) it still causes the same error.
Function ImportTransactions()
Dim objConnection, objCommand, objRecordset, strOracle
Dim strSQL, objRecordsetInsert
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "DSN=*****;UID=*****;PWD==*****;"
Set objCommand = CreateObject("ADODB.Command")
Set objRecordset = CreateObject("ADODB.Recordset")
Exit Function
End Function
It does both the import and update and seems to throw this error after.
Thanks in advance for any help,
Clare
The following fix worked for me: I created a .bat file and added the following line cscript vbsFile.vbs