Trouble converting Crosstab SQL into VBA - sql-server

I am having trouble converting/formatting a crosstab query SQL for VBA. I am getting a syntax error: expected something between the beginning of the request and the 'TRANSFORM' keyword.
I know that having the SQL start with the TRANSFORM command is most likely the issue, but after searching I have yet to find a solution.
I changed the "strSQl" to "strCrosstabQuery, but am still returning the same error.
Any assistance would be greatly appreciated.
See below for my current VBA.
Sub NewWorkRegional()
Sheets("Create Raw").Select
Range("A2:O" & Cells(Rows.Count, "A").End(xlUp).Row).Clear
strConn = "Provider=MSDASQL.1;Password=XXXXXXXX;Persist Security Info=True;User ID=KRATDAN;Data Source=DWPROD"
Set cn = New ADODB.Connection
cn.Open strConn
cn.CommandTimeout = 0
Dim strCrosstabQuery As String
strCrosstabQuery = "TRANSFORM Count(DNS_SBX_rpt_v_dm_all_work_orders.work_order_number) AS CountOfwork_order_number" & _
"SELECT DNS_SBX_rpt_v_dm_all_work_orders.sub_type_level_2" & _
"FROM DNS_SBX_rpt_v_dm_all_work_orders" & _
"WHERE (((DNS_SBX_rpt_v_dm_all_work_orders.reporting_region)='pacific') AND ((DNS_SBX_rpt_v_dm_all_work_orders.create_date) Between Date()-16 And Date()-3))" & _
"GROUP BY DNS_SBX_rpt_v_dm_all_work_orders.sub_type_level_2" & _
"PIVOT [create_date]+7-Weekday([create_date],7);"
'updated line above
Set rs = New ADODB.Recordset
rs.Open strCrosstabQuery, cn
Sheets("Results").Range("B92").CopyFromRecordset rs
End Sub

Related

Connect to SQL Server local database

I'm writing a macro in Microsoft Excel that makes an update in a table of my local SQL Server database,.
My connection string:
sConnect = "Driver={SQL Server};Data Source=(localdb)\MSSQLLocalDB;Database=Scrape;"
I get this error:
Data source name not found and no default driver specific
How do I write the connection string?
Ok, this should be pretty simple. See the link below.
https://www.erpsoftwareblog.com/2017/01/microsoft-excel-connections-sql-databases/
Also, check this out.
https://www.connectionstrings.com/sql-server/
Finally, to update a SQL Server table with Excel/VBA code, do the following.
Sub UpdateMyTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim rngName As Range
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=MyServer; " & _
"Initial Catalog=MyDB;" & _
"User ID=User;" & _
"Password=Pwd;" & _
"Trusted_Connection=No"
Set rngName = ActiveCell
cnn.Open cnnstr
uSQL = "UPDATE MyTable SET Field = 1 WHERE Field = ' " & rngName & " ' "
'Debug.Print (uSQL)
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
Post back, with specific details, if you have issues with this code. Thanks.

runtime error 3704 on a opened object

I am struggling with this situation
I have a query that when i run in MSSQL server management studio it gives me 18 rows, it it stored in a cell. The database is connected to a live server and we would like to create Excel dashboards out of them so it get refreshed with live data and create graph etc....
***** EDIT *****
I tried a very simple query and it works i can get for example
select max(datetime)from table and i do have the latest sync.
The thing is: my query has
1) A Declared table for validation
2) A temporary table "with table as( ) ;" that sorts all data and rank them with some filtering "RowNumber" that is called later in with a where statement that take only some row numbers to avoid repeats
I think that in between the connection must close, can it be?
Normally this code works out but for this server i get:
"runtime error 3704 operation is not allowed when the object is closed"
I've searched the forum and the google with no luck
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim query As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
strCon = "Provider=SQLOLEDB.1;" _
& "Password=*******;" _
& "Persist Security Info=True;" _
& "User ID=********;" _
& "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"
con.Open (strCon)
rs.ActiveConnection = Con 'modified with suggestion below
strSQLQuery = Worksheets("Query").Range("B2").Value
rs.Open strSQLQuery
For i = 0 To rs.Fields.Count - 1
Sheet2.Cells(1, i + 1) = rs.Fields(i).Name
Next i
Worksheets("Result").Range("A2").CopyFromRecordset rs
rs.Close
Set rs = Nothing
con.Close
Set cn = Nothing
Can a magician help me out? because now im doing it with excel VBA as a demo but i would like to promote it to a VB tool and want to make sure it is not a server related issue.
Thank you in advance
con.Open (strCon)
rs.ActiveConnection = strCon
should be
con.Open strCon
rs.ActiveConnection = con
ie. you should set ActiveConnection to the Connection object you just opened, not to the connection string.

Execute SQL Query from excel

I'm a bit stuck for a while in a small project
to generate results from several
sql queries in several excel Sheets, I am trying to use SQL Server 2008 and it's the first time I code VBA
I tried this code (for a SQL single query) but I still have compilation problems
Sub New_Feuil1()
ThisWorkbook.Activate
'First clear the contents from the query
Worksheets("Feuil1").Select
Range("A2").Select
Do Until ActiveCell = ""
ActiveCell.Offset(1).Select
Loop
Range("A4", ActiveCell.Offset(-1, 3)).ClearContents
'Get reporting date
ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1")
'Format the value for use in the SQL query
ReportingDateFor = Format(ReportingDate, "yyyy-mm-dd")
Worksheets("Feuil1").Select
Range("A1").Select
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim StrQuery1 As String
Dim ConnectionString As String
ConnectionString ="ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=187.125.254.231;" & _
"Database=database;" & _
"UID=sa; PWD=pwd"
cnn.Open ConnectionString
cnn.CommandTimeout = 900
'Queries to be executed
StrQuery1 = StrQuery1 & "Select Id from Users"
rst.Open StrQuery1, cnn, adOpenForwardOnly, adLockReadOnly
rst.Close
Debug.Print "StrQuery1:"; StrQuery1
cnn.Close
ThisWorkbook.Sheets("Central Dashboard").Select
Sheets("Feuil1").Range("A2").CopyFromRecordset rst
End Sub
is there any other solution ?
it seems you are new to programming :).. before you use any variables please declare them this will help you to understand them quickly.
like:
Dim ReportingDate as Date
ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1")
Dim ReportingDateFor As String
ReportingDateFor = Format$(ReportingDate, "yyyy-mm-dd")
also check your connection string. try this connection string.
ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd"
Apart from that, looking at your code you are connecting to server, opening recordset, closing recordset and finally closing the connection AND THEN trying to retrieve the results. logically this will never work :) :)
try this:
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim cmd As ADODB.Command
Dim ConnectionString As String
ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd"
cnn.Open ConnectionString
'Queries to be executed
Dim StrQuery1 As String
StrQuery1 = StrQuery1 & "Select Id from Users"
'Prepare SQL execution
cmd.Name = "SelectUsers"
cmd.ActiveConnection = conn
cmd.CommandText = StrQuery1
Set rst = cmd.Execute
If Not rst.EOF Then
With Sheets(1).Cells ' Enter your sheet name and range here
.ClearContents ' clears the entire sheet
.CopyFromRecordset rst ' copy the result
End With
Else
MsgBox "no records found.."
End If
'After work done close connection
On Error Resume Next
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing

Updating SQL SERVER Database from EXCEL

I have an excel sheet with some data:
1. Inventory item number
2. Description
3. Inventory Database ID (PRIMARY KEY)
I have about 1000 rows. I want to delete the item numbers in the database that match the item number in my excel list. I can write an application to do that in .NET, but that just seems overly complicated.
Is there an easy way through excel or SQL Server to run a sql statement to delete item numbers in my excel sheet with out the trouble of creating an application?
For quick updates. I find this to be the best method.
Add a column to Excel and construct your update statement as a formula, ie:
="DELETE Table1 WHERE ItemNumber='"&A1&"' AND InventoryId = "&C1
Copy the formula down, and copy/paste the result into an SQL window and run it.
Pro tip, if you have a lot of apostrophes to deal with, it might be worth it to do a global find/replace beforehand. Or you can deal with them from the formula. ie:
="DELETE Table1 WHERE ItemNumber='"&SUBSTITUTE(A1,"'","''")&"' AND InventoryId = "&C1
If you do not want to go through a SQL interface, you can run the attached code from excel, after updating the connection string obviously.
Sub ExecuteSQLCommand()
'Execute the SQL string passed through
Dim conn As ADODB.Connection, strConn As String, sSQLCommand As String
Dim cmd As ADODB.Command, lLoop As Long, lLastRow As Long
Set conn = New ADODB.Connection
conn.ConnectionString = "Provider=SQLOLEDB;" & _
"Data Source=DCC08SQL;" & _
"Initial Catalog=HarvestPress;" & _
"Integrated Security=SSPI;" & _
"Database=HarvestPress;" & _
"Trusted_Connection=True;"
conn.Open
Set cmd = New ADODB.Command
lLastRow = Cells(Rows.Count, 1).End(xlUp).Row
With cmd
.ActiveConnection = conn
.CommandType = adCmdText
For lLoop = 1 To lLastRow
sSQLCommand = "DELETE FROM Table1 WHERE ItemNumber='" & Cells(lLoop, 1) & "' AND InventoryId = " & Cells(lLoop, 1)
.CommandText = sSQLCommand
.Execute
Next lLoop
End With
conn.Close
Set conn = Nothing
Set cmd = Nothing
End Sub

Excel 2003 VBA Write to SQL Server 2000 ADO

We are working on changing an existing excel form to deliver a record to our SLQ server.
We have been scuccessful with code that scrubs captures and writes the data to the server using a DSN and ODBC.
scn = dsn=ODBC123
Our target users (of wich there are many) are using excel 2003 and an ODBC connection on each terminal is not practical.
This is my first venture into using ADODB.
I was tripping my badSQL message but do not get an error from the server, until I added the UID and Pass.
Now I am getting
Run-time error '-2147467559(80004005)':
Automation error
Unspecified Error
Would one of you fine ladies and/or gentlemen take a look and provide some guidence?
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim ssql As String
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
Const scn As String = "Provider=SQLOLEDB.1;Integrated Security=SSPI;" & _
"Persist Security Info=False;" & _
"Initial Catalog="DB on Server";" & _
"Data Source="Server Name" & _
"User ID=Form;Password=nope;"
ssql = "sql statment that writes a record to a table using info in the excel form," & _
" writen in vb that has worked through an odbc"
With cn
.CursorLocation = adUseClient
.Open scn
.CommandTimeout = 0
Set rst = .Execute(ssql)
End With
On Error GoTo badsql:
rs.Open ssql, cn, adOpenStatic, adLockOptimistic
On Error GoTo badsql:
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
MsgBox ("This record was updated in the database and documented for" & _
" processing. Please close this workbook.")
badsql:
MsgBox ("This record was not processed please resubmit.")
Exit Sub'
We seem to have both rst and rs as Recordset objects. I don't see a declaration for rst in the supplied code.
In any case, the query string in ssql is run twice. Once when it gets executed and the results (if any) returned into rst. The other time when rs is opened.
You probably only want to run the query string once and, as it seems to be an INSERT-type query, you probably want to use cn.Execute rather than rs.Open

Resources