Add an attachment to remote SQL server through Access - sql-server

I am using Access 2010 and SQL server 2008. I have to capture an attachment in one of my forms and move the attachment to SQL server. Server is remote and I am not allowed to provide path of the file relative to server.
Here are things I tried without any success:
1.Tried using ADODB.Stream but I get error when i use convert function(to convert the data into varbinary) after getting file value using .Read function of the object
2. Tried creating an attachment type in my form and inserted the attachment in a local access DB table with data type as Attachment. I could not move the data from this table to SQL server table.
Any pointers or solution will be of great help.
Thank you

I got it figured out. Thank you for all the suggestion guys.
All I did was create a ADODB.Stream object, read the file and passed it to a proc in sql server which inserts the data.
The code for inserting the data looks something like this
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim coll As Collection
Set conn = New ADODB.Connection
Set coll = New Collection
stConnect = GetADOConnectionString()
conn.ConnectionString = stConnect
conn.Open
If conn.State = 1 Then ' open
Set cmd = New ADODB.Command
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "proc_insert_review_doc"
cmd.ActiveConnection = conn
coll.Add cmd.CreateParameter("#LoanID", adVarChar, adParamInput, 10, LoanId)
coll.Add cmd.CreateParameter("#WorkStreamID", adVarChar, adParamInput, 10, WorkstreamID)
coll.Add cmd.CreateParameter("#QuestionSetID", adVarChar, adParamInput, 10, QuestionSetID)
coll.Add cmd.CreateParameter("#FileValue", adVarBinary, adParamInput, , FileValue)
For Each coll_i In coll
cmd.Parameters.Append (coll_i)
Next coll_i
cmd.Execute
Set cmd = Nothing
conn.Close
Else
MsgBox "Failed to open a connection to the database server!", vbCritical
End If
Set conn = Nothing
End Function

i'll do somthing like that, it is looking easyier to me to use a record set...
dim Conn as ADODB.Connection
dim RS as ADODB.RecordSet
dim binObj as ADODB.Stream
Conn.ConnectionString="Provider=SQLOLEDB;Persist Security Info=False;User ID=sa;Password=;Initial Catalog=khc405;Network Library=dbmssocn; Data Source=db1;"
Conn.Open
Set RS = New ADODB.Recordset
sql = "SELECT * FROM SOMETABLE WHERE FILENAME='HOWTO.PDF'
RS.Open sql, GLBcn, adOpenDynamic, adLockOptimistic
If Not (RS.BOF And RS.eof) Then
Set binObj = New ADODB.Stream
binObj.Type = adTypeBinary
binObj.Open
binObj.LoadFromFile (App.Path & "\SomeFolder\" & ''HOWTO.PDF''
RS!FILEDATA = binObj.Read
RS!FileName ='HOWTO.PDF'
RS.Update
binObj.Close
Set binObj = Nothing
End If
i get this from-
http://www.sqlservercentral.com/Forums/Topic243427-169-1.aspx
good luck

Related

VBA to open and run .sql file and copy the result in excel

I am a bit new to this so my apologies in advance for any mistakes. I am trying to open and execute a sql query which is saved in C drive. The sql works fine. I did not write that sql and it is a very big file so would not like to add the code in VBA. I have been searching on this site and other places but struggling to make this work. I have had some or the other problem each time. I am pasting the code below for you to have a look and help me please. I have created this function which I am using in my VBA code.
Public Function ss()
'Open Connection
Dim oCon As ADODB.Connection
Set oCon = New ADODB.Connection
'Set Connection String
Dim sCon As String
sCon = "Provider=SQLOLEDB;Persist Security Info=True;User
ID='*****';Password='*****';Initial Catalog=****;Data Source=*******;Use
Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption
for Data=False;Tag with column collation when possible=False"
oCon.Open sCon 'Connect established
'Create recordset
Dim ps As ADODB.Recordset
Set ps = New ADODB.Recordset
'Set & execute SQL Command
Dim pCMD As ADODB.Command
Set pCMD = New ADODB.Command
Set pCMD.ActiveConnection = oCon
Dim filename As String
filename = "C:\Users\???????????\******.sql"
'select data
pCMD.CommandText =
CreateObject("scripting.filesystemobject").opentextfile(filename).ReadAll()
Set ps = pCMD.Execute(, , adCmdText)
Debug.Print ps.GetRows
If ps.EOF = False Then Sheets("Sheet2").Range("A1").CopyFromRecordset ps
'Close connection
Set ps = Nothing
Set pCMD = Nothing
oCon.Close
Set oCon = Nothing
End Function
Debug.Print has only been used to see the result but it is showing the same error "Run-time error '3704' Operations is not allowed when the object is closed. After trying so many different things I am not sure what is it that I am doing wrong.
Can someone please help?
Any help will be really appreciated.
For me the easiest solution for you is to modify the end of the stored procedure so when executed, it insert all the results in a table. The next time you execute the SP you just have to TRUCATE the table and INSERT new results.
Execute the SP
You can call the SP from Excel with VBA using some code you can find here on StackOverflow, for example the following (which I've taken from this answer):
Dim cnn As Object
Set cnn = CreateObject("ADODB.Connection")
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
cmd.CommandType = 1 ' adCmdText
cmd.CommandTimeout = 120 ' number of seconds to time out
Dim ConnectionString As String
cnn.ConnectionString = "driver={SQL Server};server=MYSERVERNAME;Database=MYDATABASE;Trusted_Connection=yes;"
cnn.Open
Dim SQL As String
SQL = "EXEC [dbo].[Procedure_make_report] 'param1'"
cnn.Open
cmd.CommandText = SQL
cmd.ActiveConnection = cnn
cmd.Execute
If Not cnn Is Nothing Then
cnn.Close
Set cnn = Nothing
End If
Retrive results into Excel
Now that the results of the SP are stored into a table of you DB you can import them into Excel with ODBC connection as shown here or with this procedure.

vba mssql connection error

I am trying to connect sql with Access.
What I want to do is simply get data from mssql using select statement.
Here is the code.
Sub ConnectSQLServer()
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
Dim par As ADODB.Parameter
Dim strSQL As String
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn
Set cmd = New ADODB.Command
cmd.CommandText = "dbo.Version"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
strSQL = "SELECT * FROM dbo.Version"
cmd.Execute
conn.Close
Set conn = Nothing
Set cmd = Nothing
End Sub
When I execute this code, I get error like "[Microsoft][ODBC SQL Server Driver][SQL Server] The request for procedure 'Version' failed because 'Version' is a table object.'
I know that I need to add something after "strSQL = SELECT * FROM dbo.Version" but I do not know exactly how to fill in.
Could you please help me with this?
It looks like you are executing dbo.Version as a SP or a SQL Command which is wrong.
You should execute the command in strSQL object instead. So after the modifications your code will look something like this:
strSQL = "SELECT * FROM dbo.Version"
Set cmd = New ADODB.Command
cmd.CommandText = strSQL
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
EDIT 1
I replicated the same issue in MS Excel to read data from MS SQl Server by using the following code and it worked for me:
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=HARSH-SHARMA\SQLEXPRESS;Initial Catalog=db1;User ID=sa;Password=pass001;"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from Subject"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
Please try this.

Return results from SQL Server stored procedure using variables in ADODB

I'm working on a rec process which will pull data out of a SQL Server database into Excel and out of another application to compare the two sources.
I've written some code that will pull the data into a ADODB record set and drop it into an Excel sheet from a SQL Server view. This works as expected.
I need the query to be more dynamic and as it is quite resource intensive in the real query. I think it would be better to use a stored procedure, passing parameters to the query and only returning the result sets I need.
I don't want the SQL query to be complicated within the VBA though which is why I can't just define the query there.
The following code returns no records to the record set and exits.
Running the stored procedure in Management Studio using the same parameter gives the results expected in SSMS.
Stored procedure:
CREATE PROCEDURE [dbo].[JoshTest]
#AccCode nvarchar(50)
AS
SET NOCOUNT ON;
SELECT
[Account_SKey], [Hierarchy_SKey], [Account_Code], [Leaf]
FROM
[dbo].[VW_DIM_ACCOUNT_LEAF]
WHERE
[Leaf] = #AccCode;
GO
VBA in Excel:
Sub test_stored_proc()
Dim AccountCodeVar As String
AccountCodeVar = Range("ACCCODESEL").Value
Dim osheet As String 'output sheet
Dim orange As String 'output range
osheet = "Output1"
orange = "A3"
Call ConnectSqlServerStoredProc(osheet, orange, AccountCodeVar)
End Sub
Function ConnectSqlServerStoredProc(osheet As String, orange As String, AccountCodeVar As String)
'Clear previous results
Sheets("Output1").Range("A3:D60000").Clear
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=CSIMCCS01; Initial Catalog=T_EXP_CPM; Integrated Security=SSPI;"
Debug.Print sConnString
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
Set cmd = New ADODB.Command
cmd.CommandText = "JoshTest"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
'set parameter values
Set prm = cmd.CreateParameter(Name:="AccCode", Type:=adVarChar, Direction:=adParamInput, Size:=10)
cmd.Parameters.Append prm
cmd.Parameters("AccCode").Value = "'" & AccountCodeVar & "'"
Debug.Print cmd.Parameters("AccCode").Value
Set rs = cmd.Execute
' Check we have data.
If Not rs.EOF Then
' Transfer result.
Sheets(osheet).Range(orange).CopyFromRecordset rs
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
MsgBox ("Done")
End Function
I looked at several examples of similar questions but they all try to return a single value, such as status / user id etc. rather than a data set.
Worked it out eventually... the issues was that I was putting single quotes either side of the parameter value. I thought that this would be correct as SQL would require them but taking them out of the VBA has resolved the issue.
#Mister 832 - thanks for your help in stepping this through.
In the end the solution was changing:
cmd.Parameters("#AccCode").Value = "'" & AccountCodeVar & "'"
to
cmd.Parameters("#AccCode").Value = AccountCodeVar
Regards
Have you tried adding an # to the parametername?
Set prm = cmd.CreateParameter(Name:="#AccCode", Type:=adVarChar, Direction:=adParamInput, Size:=10)
cmd.Parameters.Append prm
cmd.Parameters("#AccCode").Value = "'" & AccountCodeVar & "'"
I got it working on my pc.
Remove the line Set rs = New ADODB.Recordset and change the recordsetline to Set rs = cmd.Execute

ADO recordset has no recordcount with source set to ADO command (stored procedure)

I have an ADO command object in VBA running and returning values from a stored procedure (in SQL Server). To validate the SP and command lines in VBA, I've used the CopyFromRecordset method to view the data and everything seems fine.
Set ADOComm = New ADODB.Command
With ADOComm
.ActiveConnection = ADOConn
.CommandType = adCmdStoredProc
.CommandText = "GenerateMasterSumIfs"
.Parameters.Append .CreateParameter("ImportFilePath", adVarChar, adParamInput, 100, TextFileSavePath)
End With
Set ADORec = New ADODB.Recordset
Set ADORec = ADOComm.Execute
I'd now like to be able to navigate the returned records using FIND or GETROWS (for example) but the recordset appears to have no data (recordset.RecordCount returns -1). I've tried to research this online and have seen references to cursor types being restricted depending on the source (in my case, SQL Server) but haven't been able to find a solution that I can understand and use.
So, my question(s), specifically, are:
Can I continue to use the ADO Command/Recordset combination to collate my data then 'navigate' it? OR
Do I need to run the SP using a different method to enable the navigation I require?
I'm no expert in this field, so would appreciate your patience with my technical descriptions and any site etiquette faux pas.
The solution I needed was the CursorLocation property of the ADO Connection object. Changing it to adUseClient has allowed me to move the cursor and use methods such as FIND and GETROWS as I required.
Set ADOConn = New ADODB.Connection
ADOConn.CursorLocation = adUseClient
ADOConn.Open "Driver={SQL Server Native Client 11.0};Server=ServerName;Database=DBName;Trusted_Connection=yes;"
Set ADOComm = New ADODB.Command
With ADOComm
.ActiveConnection = ADOConn
.CommandType = adCmdStoredProc
.CommandText = "GenerateMasterSumIfs"
.Parameters.Append .CreateParameter("ImportFilePath", adVarChar, adParamInput, 100, TextFileSavePath)
.Parameters.Append .CreateParameter("MTFilePath", adVarChar, adParamInput, 100, PathToMT)
End With
Set ADORec = New ADODB.Recordset
Set ADORec = ADOComm.Execute

MS Access to Execute Proc in SQL Server

I have a Proc for creating and updating a table in SQL Sever. The result table is linked to the MS ACCESS FE. It was before created by Macro involving queries in MS Access. How could I call or execute the Proc from MS Access FE.
I tried this code but it doesn't result in anything.
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = "Provider=SQLNCLI11.1;Security=SSPI;Initial Catalog=MYDB;Server=MyServer;Integrated Security=SSPI;"
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "UPDATE_DATA"
cmd.Execute
I'm new to VBA Coding. Any help or leads will be greatly appreciated.
In your code, you haven't opened a connection to the database. Open a connection first like in the below code:
Private Const gcConn As String = "Provider=SQLNCLI11.1;Security=SSPI;Initial Catalog=MYDB;Server=MyServer;Integrated Security=SSPI;"
Sub UpdateProc()
Dim oDB As ADODB.Connection
Dim oCM As ADODB.Command
Set oDB = New ADODB.Connection
oDB.Open gcConn
Set oCM = New ADODB.Command
With oCM
.ActiveConnection = oDB
.CommandType = adCmdStoredProc
.CommandText = "UPDATE_DATA"
.Execute
End With
oDB.Close
Set oDB = Nothing
End Sub
Simply save your command as a pass-though query. Thus your query is:
UPDATE_DATA
Then this one line of code will run that query
CurrentDb.QueryDefs("MyPass").Execute

Resources