Convert t-SQL query with Cursor to Microsoft Access - sql

One of my managers created a Access database and is working on some data analysis - what if scenarios. Based on different conditions, he produces a report in Access.
He asked me to do some data manipulation, so I imported the database into SQL and wrote a routine with a cursor that'll do what he wants. I then export the results back into Access. Before I get any heat for using a cursor, this was supposed to be a one time only deal, so that was the fastest way for me to get it done.
As you'd expect, now he wants me to run it all the time and asked me to convert my routine to Access so he can just run it. Before you tell me to just use SQL, he's very set on Access and is often traveling and off line.
So, my question is: is there a "easy" way to convert a T-SQL query with a cursor into Access? It's been a long time since I worked with Access, but I suspect it'd have to be re-written in VBA. I'm thinking that maybe another solution would be to call the query from Access and run it in SQL, but I don't know if that can be done or if it'd work on my case because of him being off line (maybe install SQL express in his laptop?)
Any suggestions would be appreciated.
Thanks,
Alex

This is how I got around it:
1.Downloaded and install SQL server express in the user's machine.
2.uploaded Access database structure and data to the local SQL.
3.created the stored procedure that I wanted to run in the local SQL server.
4.back in Access, deleted all the tables and recreated them as linked tables to SQL
5.Create a form in Access with a big button that executes the stored procedure
`Private Sub Command0_Click()
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef("")
qdf.Connect = CurrentDb.TableDefs("ANY TABLE").Connect
qdf.SQL = "EXEC dbo.[stored procedure name]"
qdf.ReturnsRecords = False
qdf.Execute
Set qdf = Nothing`
The stored procedure truncates one re-populates one of the tables. So after executing it I can open up the table in Access and see the changes. My manager can continue to use Access and SQL server is used in the back-end. Happy Ending! :)

Related

Executing T-sql query from hard drive

I have T-SQL queries stored on a hard drive: I:\queries\query1.sql and I:\queries\query2.sql.
I usually work in a way that I execute a query from a drive, and then I copy results into Excel, and then I work on it.
My problem here is that query1.sql is already long, and now I would like to extend it by getting a result of query2.sql, and join it with a result of query1.sql.
What I could do is appending a code from query2.sql to query1.sql. But then the query is getting really long and hard to maintain.
I would like to do something like this:
SELECT * FROM ("Result of I:\queries\query1.sql") q1
LEFT JOIN ("Result of I:\queries\query2.sql") q2 ON q1.ID=q2.ID
Is there any way to write a query or stored procedure, which will be again stored on a drive to do this?
Basically, you need to ask your DBA for a database when you are able to store things in the database. This can be on the same system where the data is stored. Or, it could be on a linked system. Gosh, you could run SQL Server locally and store the information and data there.
Then, the queries that you are storing in files should be views in the database. You can then run the queries and store and combine the results locally.
You are essentially recreating database functionality using text files and data files -- going through a lot of effort when SQL Server already supports this functionality.
To expand on Gordon's comment (+1), why are you running scripts off of a drive? Most DBA's I've known would treaten bodily harm over this as executing code that they can't control / troubleshoot / see source code control on brings a whole host of security and supportability issues.
Far better to store this code in a Stored Procedure, which will have a saved query execution plan, can be tracked using various DMV's, and have permissions assigned to it, then your outside Excel doc can just set a connection and execute the SP.

Query References Another - Access to SQL Server

Good morning,
I just received a new assignment and I am struggling with finding an appropriate solution. I have searched through the SO Forums, and through Google, but have not found a workable solution. Below is my scenario:
We are working out of Microsoft Access to connect to an SQL Server Database via an ODBC Connection.
I wasgiven an incredibly large pass-through SQL query, larger than is able to be processed in MS Access. In this pass-through query, there is a subquery in a WITH...AS method.
I am hoping to be able to split this one, singularly large, SQL pass through query into two: Query One (the subquery), and Query Two (which references the results of the subquery)
I know that by using general Access queries, I can write a Macro like follows...
Sub myQuery()
' Edited from http://www.dbforums.com/showthread.php?1667831-Run-multiple-queries-in-sequence-on-click
' On Error GoTo ErrHandler
' Run the first query
MsgBox "Starting first query"
DoCmd.OpenQuery "first_Query"
DoEvents
' Run the second query
MsgBox "Done. Now starting second query"
DoCmd.OpenQuery "second_Query"
DoEvents
MsgBox "Done!"
End Sub
However, these need to be pass-through queries. I believe that the enormously large SQL String is created via a number of user inputs. Regardless, I don't have the ability to change the pass-through SQL that I was given.
Is there anyway I can write a macro that calls the first pass-through query, and then calls the second pass-through query that REFERENCES the result of the first?
Here is an example with what I am working with...
WITH queryOne AS
(
SELECT fooID
FROM tblFoo
WHERE foodate > ...
)
SELECT foo, fooone, footwo, foothree
FROM tblOtherFoo
WHERE fooID = OtherFooID
However, the query is 50000+ characters, exceeding that ~37k limit.
Please feel free to ask any questions. I am stumped by this and would appreciate any feedback or alternative resources.
Thank you!
It not clear what you mean by something that references the first or previous? Why break up something you been given that supposed works just fine?
So just place that existing t-sql you been given into a stored procedure. In T-SQL you can easy have some SQL operate on some previous SQL, but why break up such a HUGE massive monster slew of code and introduce bugs? It will take you YEARS AND YEARS to break up a KNOWN working huge T-SQL that been built and developed for you (something that long likely took a few years and a team of developers to create).
A conservative estimate would be such a routine cost $50,000, or even $100,000 to develop.
No question that the working T-SQL you been given might reference previous data, or even do selects into #Temp tables that additional T-SQL can work on.
If you ALREADY have a working PT code and query given to you?
Simply take that T-SQL query, and simply paste it into a stored procedure. You will do this in SQL Server and NOT even touch or bother with Access.
So don't create some macro in Access that calls multiple separate queries, but place all of the T-SQL in a stored procedure, and simply call that huge mess one time from Access.
It possible that the T-SQL you been given is incorrect, but assuming that the T-SQL is correct, then simply place all that long mess into a working stored procedure. You do not place this SQL in MS Access and you don’t need to have that mess inside of Access.
So get that T-SQL working in SQL Server – don’t bother with MS Access until this long query mess is working in SQL Server. ONLY THEN do you fire up Access.
So you THEN create a simple PT query in Access that calls the huge long T-SQL mess you been given. But that “mess” is to be placed in SQL Server – not in Access.
So create a PT query in Access that calls your “supposed” working T-SQL you been given. The SQL you save in the Access PT query will be this
Exec my_StupidLongSQLProc
Save the above as a PT query. Then in VBA code go:
Currentdb.QueryDefs("MyPTQuery").Execute
If you need to pass some values from Access, then go:
With CurrentDb.QueryDefs("MyPTQuery")
.sql = "exec My_StupidLongSQLproc " & p1 & "," p2
.Execute
End with
In above we pass two VBA values from Access to the big mess of sql you have – the stored procedure in above is just an example that access two parameters passed from Access VBA. If the T-SQL you been given does not require values from Access, then the first single .execute will do the job.
And if you REALLY did get such a long routine that is correct T-SQL, then it likely already has parameters in the working T-SQL (and again you don’t want to mess with or change such a huge long working T-SQL that you been given).
So you only need one line of code in Access, and your existing long T-SQL you been given if written correctly can be placed in a stored procedure (assuming that you actually been given a correctly working PT query).
So if you REALLY did get a huge massive working T-SQL statement, then simply place that KNOWN AND WORKING T-SQL in SQL Server as a stored procedure and call it with one line of code as per above.
So trying to split this up from Access will only server to cause world-wide poverty and ANY tiny miss step or breaking up of that huge long routine will cause world-wide poverty and starving children as you try and “fix” this great working T-SQL that you been given. As noted, something that long to create would take a teams of developers HUGE resources. If you touch or break up one line of code and mess it up, then you need that team of developers to spend several months trying to fix what you broke.
So the INSTANT you start breaking up such a huge long mess is the instant you lost this battle and will waste several years of your life trying to fix this crazy long T-SQL that you been given that is already claimed to be proper working code.

"Select data source" popping-up when executing a SQL writed query

I try to create a pretty complex database on ms Access 2013, so I wanted to type it directly in SQL. It has no errors, as other DBMS can fully build the database from the script I wrote (for example, phpmyadmin imports it with no difficulty).
On this tutorial, it is showed how to write a SQL query in order to build tables. I thought this way matched well with my goal as I could copy-paste my script in the query and run it to create the whole thing.
But when I tried to open/double-click on the query a pop-up appears saying "Select data source", waiting for me to select an ODBC, either from a file or a host, before continuing and executing the query.
I tried other types of queries (creating only one table at time, trying on a blank file, or even SELECT * FROM *), bt this message keeps showing up and I really don't know how to deal with it as I don't want to connect to anything but the infile database.
Does anyone got a hint about what to do in this case?
Or, even better, how could Access import my SQL script in order to create the database?
You should configure the database connection in the ODBC and check whether the connection is established or not. Once the connection is established, you can run the query to fetch the data or create tables as per your requirement.

How to do a search and replace of a part of a string in all columns in all tables in an sql database

Is it possible to search and replace all occurrences of a string in all columns in all tables of a database? I use Microsoft SQL Server.
Not easily, though I can thing of two ways to do it:
Write a series of stored procedures that identify all varchar and text columns of all tables, and generate individual update statements for each column of each table of the form "UPDATE foo SET BAR = REPLACE(BAR,'foobar','quux')". This will probably involve a lot of queries against the system tables, with a lot of experimentation -- Microsoft doesn't go out of its way to document this stuff.
Export the entire database to a single text file, do a search/replace on that, and then re-import the entire database. Given that you're using MS SQL Server, this is actually the easier approach. Microsoft created the Microsoft SQL Server Database Publishing Wizard for other reasons, but it makes a fine tool for exporting all of the tables of a SQL Server database as a text file containing pure SQL DDL and DML. Run the tool to export all of the tables for a database, edit the resulting file as you need, and then feed the file back to sqlcmd to recreate the database.
Given a choice, I'd use the second method, as long as the DPW works with your version of SQL Server. The last time I used the tool, it met my needs (MS SQL Server 2000 / 2005) but it had some quirks when working with database Roles.
In MySQL, you can do it very easily like this:
update [table_name] set [field_name] = replace([field_name],'[string_to_find]','[string_to_replace]');
I have personally tested this successfully on a production server.
Example:
update users set vct_filesneeded = replace(vct_filesneeded,'.avi','.ai');
Ref: http://www.mediacollege.com/computer/database/mysql/find-replace.html
A good starting point for writing such a query is the "Search all columns in all the tables in a database for a specific value" stored procedure. The full code is at the link (not trivial, but copy/paste it and use it, it just works).
From there on it's relatively trivial to amend the code to do a replace of the found values.

access to SQL copy

We have an Access DB which has a set of local tables and input forms etc. in which a user maintains their data.
We also have a SQL DB with the same tables which is used to displays the data in a web search form.
What is the best way to allow the user to udate his changes to the SQL db while keeping the working copy local so he can work offline and then push the files when he is happy with new version of the data?
My first thought was add the SQL tables as linked tables I could then truncate (access does like that) or delete the content in each table and then do an insert for each table.
Can I call a SP from access on the SQL to truncate the tables as I am have problem running deletes
I really do want to get it down to the user running a macro/sql call that is repeatable etc.
Thanks for your help
You should be able to use the ADODB.Command object to execute stored procedures.
EDIT:
This example is copied from Using ADO in VB and Access
Sub ADO_COMMAND_CONNECTION_TEST()
Dim cmd As New ADODB.Command
Dim rs As ADODB.Recordset
Dim strConn As String
cmd.ActiveConnection = " DRIVER={SQL Server};" & _
"Server=UKDUDE;DATABASE=pubs;UID=sa;PWD=;"
cmd.CommandText = "byroyalty"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Refresh
cmd.Parameters(1).Value = 25
Set rs = cmd.Execute
' Recordset now has authors with 25% royalty.....
End Sub
Don't ever use MS Access linked tables with MS SQL.
Not only are they slow, but Access can leave open client-side write cursors on the tables referenced. That's a really dumb way to create lots of deadlocks, but Access does it anyway.
Microsoft significantly improved this when they added Access Data Projects - in these the entire back end is replaced with SQL and Access just supplies the forms.
If you want user actions to write directly back then ADPs are by far the best method.
If you want to cache changes locally in your Access DB and then send them up to SQL you have a far more complex problem. You will need to be far more specific on exactly how you want synchronisation to happen - for instance if two users make offline changes who wins when they connect?
I don't understand why you just don't link directly to the SQL Server data and use it directly, rather than going to the trouble of maintaining a second copy of it. This is the standard Access way to do things -- why are you resisting the natural capabilities of the tool you're using?