Question

SQL newest records query

Asked by: wesbrowning

I'm using the solution outlined at: http://www.experts-exchange.com/Databases/FileMaker/Q_21732690.html to create a query to an SQL server. However, it doesn't seem to be working to get all the newest records. Am I doing something wrong? Here's that part of the SQL query....

WHERE "Orders"."Date_Added" > "Orders"."Date_Added"
    OR "Orders"."Date_Modified" > "Orders"."Date_Modified"

I want to download only the newest records- so that I don't have a bunch of duplicates in my database. FYI- the server I'm reading from doesn't keep different "versions" of the order...it only overwrites data as it's updated...so we have the need to keep historical data.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-02-28 at 09:12:11ID21754910
Tags

sql

,

newest

,

record

,

query

Topic

FileMaker Pro Database

Participating Experts
1
Points
500
Comments
17

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Xcopy syntax needed to copy and overwrite the newest fil…
    I want to use robocopy xcopy for the backup of two db files. Currently the sql server keeps about 5 backups for each. The directory layout looks like this: dbfile dbfile_db_200410292000.bak dbfile_db_200410302000.bak dbfile_db_200411012000.bak so I want to copy the newest...
  2. Having the newest record
    Hi there, I have two table, one with customers and one with articles bought for this customers. I would like to have using a SQL query, the name of the customer and the newest article that the customer have bought. Example Table Customers Customer_ID Name Surname...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: billmercerPosted on 2006-02-28 at 10:26:36ID: 16067852

Is this the exact query string you're using? As written, it's looking for all records with dates greater than their own dates, which doesn't really make sense. It needs an actual value to compare the Date_Added field to. This could be an actual static value, or the result of some sort of calculation. That calculation could be done on the SQL server, or could also be done within FileMaker.

Does the SQL server have a flag or indicator field to show whether or not it has been imported into FM? If so, you can probably do the calculation on the SQL server. You could use a subquery and the max() function to supply the date for comparison, which might look something like this...

 WHERE "Orders"."Date_Added" >  (SELECT MAX(Some_Date) FROM
   Orders where Orders.Flagged_As_Exported= 1) OR...



> doesn't keep different "versions" of the order...it only overwrites data as it's updated.
Does this mean your SQL server is actually re-using the same order record for multiple different orders? Or are you just saying that a given order can be edited or modified in-place?




 

by: billmercerPosted on 2006-02-28 at 10:48:55ID: 16068081

If the information needed to decide what date range to use isn't available on the SQL server, you'll need to get it from FileMaker. You can do this by creating your SQL query string using FileMaker string calculations. Using a script or calculated field, you create the SQL query string by piecing together chunks.
For example, suppose you have a FileMaker field called "FM-LastExportDate", and you want to use a query like this:

  select * from orders where orders.date_added > some-date-from-filemaker
  or orders.date_modified > another-date-from-filemaker

To submit this string with the date value filled in, use the option to get the SQL query from a calculation, and use string concatenation to build the actual text of the query string.

  SQLQueryString = "SELECT * FROM ORDERS WHERE Date_Added = " & FMDateAdded & " OR Orders.Date_Modified = " & FMDateModified

Now the SQLQueryString field contains the query needed to return the newest results, based on values in FileMaker.

This is more awkward to describe than it is to actually do.

 

by: wesbrowningPosted on 2006-02-28 at 11:47:05ID: 16068676

In your example, where do I use the field, "FM-LastExportDate"?

 

by: billmercerPosted on 2006-02-28 at 19:01:59ID: 16072010

That would be a value from the FileMaker database, either a calculation, a field, or a script variable, which contains the variable portion of the query string. I just made up an arbitrary field name, you'd probably be using a field that already exists in your database.
 
A couple of things to be aware of...

Quotation marks (double quotes) are used by FileMaker to delimit the beginning and end of a text string. If you need to include double quotes in your query string, you'll have to add those in by using the backslash character in front of the quotation mark, like this:
  \"
This tells FileMaker that you want that quotation mark to be included inside the string rather than indicating the end of the string. Single quotes are ok, and don't need any special treatment.

Also, you'll need to make sure that the date format used is one that's acceptable to the SQL server, so you might need to change the formatting of the date field when putting it into the query string.

 

by: wesbrowningPosted on 2006-03-03 at 11:28:10ID: 16097421

I submitted this string....
"SELECT * FROM ORDERS WHERE Date_Added = " & Local_System_Settings::gCurrentTime & " OR Orders.Date_Modified = " & Local_System_Settings::gCurrentTime

It returned the following error...
ODBC Error: [Actual][SQL Server] Incorrect syntax near the keyword 'OR'.


What happened? Also, will this return results that meet both criteria that I want (new records and updated ones)?

 

by: billmercerPosted on 2006-03-04 at 14:38:29ID: 16105260

The string I provided is not a valid SQL query string on its own. It's intended to be evaluated by FileMaker as a calculation, and then the results of that calculation should be submitted as the query string.

Also, my example was typed off the top of my head, and probably doesn't meet the syntax requirements of your SQL server's ODBC driver. It could be that you need the quotation marks around the field identifiers, as you posted originally, for example.

Also, I used Date_Added for the first field, but Orders.Date_Modified for the second. You'll want to make them consistent, one way or the other.  
 
It may help you to divide the process into steps.

First, manually create a query string that produces the results you want. (This might be the hardest part)

Next, create a calculated field which evaluates to produce the same query string you created manually.
Tweak the calculation until it returns a result that looks exactly the same as the query string you know works.
Then, use the results of that calculation as the query string for your SQL query.

>Also, will this return results that meet both criteria that I want (new records and updated ones)?
That depends on exactly how your tables are defined and how you're using those fields.
Here's what that query will do:
It will create a result set that includes any SQL records where the Date_Created field is LATER than the date specified in that FileMaker field, or the Date Modified field is LATER than that same Filemaker date.
If you could have multiple entries on one day, you would also need to take the TIME into account.  

The formula I provided can be used as a reference, but if you want an exact example of how to create your specific query from within FM, you'll need to post the exact full text of your query, and the exact names of your tables and fields from both the SQL and FileMaker databases.
 
 

 

by: wesbrowningPosted on 2006-03-04 at 21:06:21ID: 16106497

I tried a few things, including your suggestions but was unable to get any further. Below is the information that might help you help me construct a bettery query string. Perhaps I should have given some of this information to you sooner. Thanks for your patience.

You should also know that the ODBC driver I have only downloads, and cannot upload. This "one-way communication" may have an affect on how (or whether or not it's acutally possible) the query is constructed. All of my examples are specific to my situation and refer to actual fields I'm using.

With my driver, I can construct a query in one of two ways to get information. Below are examples of the first way I can do it. This first example shows a query from one table and one field from that table. The second example shows all fields from one table. The second way I can construct the query is through calculated text.

Ex 1:
SELECT "Orders"."Location"
FROM "Orders"

Ex 2:
SELECT *
FROM "Orders"


I would like to compare the local time (established in Filemaker, see below) with the remote records to decide what records it needs to download. It would need to download any record that is new, or that has been updated. The two fields on the SQL database that use a timestamp for the records are:
"Orders"."Date_Added"  and  "Orders"."Date_Modified" (it returns a timestamp like this: 2/28/2006 1:46 PM)

The field I'm using in Filemaker to establish the current time is: Local_System_Settings::gCurrentTime (it's format for a timestamp is: 3/4/2006 10:57:13 PM)

It is possible for us to have multiple entries in one day (we're querying the server every 5 minutes).

 

by: billmercerPosted on 2006-03-06 at 18:34:58ID: 16120665

OK, let's start out with a simpler scenario and then work up to the more elaborate query, so we can figure out where it's going wrong.

- Create a new FileMaker script, and insert an Import Records script step.
- Check the box at the bottom that says perform without dialog.
- Specify Data Source, and choose ODBC as the source.
- Select the ODBC DSN for your SQL server, and any user/password required
- Don't use the "query builder" function. Instead, select "Calculated SQL Text" as the source of the query.
- In the calculation box, enter this text:

   " SELECT \"orders\".\"Location\", \"orders\".\"Date_modified\" FROM \"orders\" "

Notice that there's a double-quote at the beginning and end of the whole string,
and notice that everywhere a double quotes appears in your original query, we're adding a backslash in front.
The backslash tells FileMaker to treat that quotation mark as just part of the string.
Specify what field you want the orders.location data to be imported into.

Now, try running the script and see if it works. If it doesn't there's a mistake somewhere, so go back and double-check things.
Once this runs successfully, then we can move on to making the query more complicated.


One other point:
If your SQL fields are actually timestamp fields, then you'll probably need to use ODBC timestamp format when specifying the criteria. This may involve some string manipulation to get the actual value looking as it should.
Basically, ODBC timestamp format looks like this:
   {ts '2005-02-15 09:30:00'}

 

by: billmercerPosted on 2006-03-06 at 18:37:41ID: 16120679

Here is a simple example file I wrote that shows how the script step is set up.
Since I don't have access to your SQL server, I created an Access MDB file, which I included in the archive, and set up an ODBC connection to it

http://www.milleniumhandandshrimp.com/upload/orders%20test.zip

 

by: wesbrowningPosted on 2006-03-07 at 06:34:39ID: 16123670

The SQL query worked. I'm moving on to work on the timestamp issue you pointed out. Where do we go from here with the SQL string?

 

by: billmercerPosted on 2006-03-07 at 12:17:15ID: 16126985

Yikes, I just realized that I uploaded the wrong FM7 database in that zip archive. Apparently you didn't need it, so no harm done, I'll upload the correct file tonight. Sorry about that!

OK, since the initial query worked, now you will want to try making it more complicated. Temporarily create a new global text field called "TimestampForQuery" or something like that.
Modify your SQL calculation string so that it looks like this:

" SELECT \"orders\".\"Location\", \"orders\".\"Date_modified\" FROM \"orders\"  
  WHERE \"orders\".\"Date_modified\" > " & TimeStampForQuery

Now go to that global text field and manually type in an ODBC timestamp string like this:
  {ts '2006-03-01 00:00:00'}
Then try running the script, make sure it imports any matching records without errors.
Try changing the value of the global text field timestamp, to make sure it's correctly returning records as you expect.

Once this is working, the next step is to take your existing FileMaker timestamp field, and convert it into that special ODBC timestamp format by using some functions and string concatenation. The easy way to do this is to change your global field into an unstored calculated text field, and define the calculation to look something like this:

"{ts " & Year ( Local_System_Settings::gCurrentTime ) & "-" &
Month ( Local_System_Settings::gCurrentTime ) & "-" &  
Day ( Local_System_Settings::gCurrentTime) & " " &
Hour ( Local_System_Settings::gCurrentTime )  & ":" &
Minute ( Local_System_Settings::gCurrentTime )  & ":" &
Seconds ( Local_System_Settings::gCurrentTime )   & " } "

This should create a text string that shows the current timestamp value in the special ODBC timestamp format. Test it out and see what happens.

It's possible depending on your ODBC driver, that you might need to do some additional tweaking to the string for it to be recognized, for example, if your driver requires the values in the timestamp to have leading zeroes in front.

But give it a try first, if it works as is, then you won't need to worry about that.

 

by: wesbrowningPosted on 2006-03-07 at 20:37:46ID: 16130283

I tried the string and got an error message stating that there was an error with the Syntax on Line 1.

I just had a random thought...

What if I just did a regular import and based on matching/updating...and importing remaining records? If you think this is a good idea and would work, how would you recommend I go about it?

 

by: billmercerPosted on 2006-03-08 at 07:10:38ID: 16134149

>I tried the string and got an error message stating that there was an error
>with the Syntax on Line 1.
At which point did you get this error? What is the exact text of the error message? It should show you the actual text of the query that caused the error, which could be due to differences in your ODBC driver and mine.
.

>What if I just did a regular import and based on matching/updating...
That would work if you want to change existing records, but it's not going to give you a history of past records. Also, won't you still need a SQL query to initiate the import?

 

by: wesbrowningPosted on 2006-03-08 at 12:16:37ID: 16137876

>I tried the string and got an error message stating that there was an error
>with the Syntax on Line 1.
At which point did you get this error? What is the exact text of the error message? It should show you the actual text of the query that caused the error, which could be due to differences in your ODBC driver and mine.
>>>I doesn't actually show me the error. This a screenshot of the error it gives me: http://www.passportcamps.org/uploads/errormessage.gif .  I tried doing a query that the "where" was based on the SQL side (comparing date_added and date_modified) and I was able to get a record. So, I'm guessing that there's just a problem in the way that we're asking it to compare the SQL with the Filemaker side. I tried this....

SELECT "Orders"."Location", "Orders"."Date_Modified"
FROM "Orders"
WHERE "Orders"."Date_Added" < "Orders"."Date_Modified"

...and it worked fine. This however is not what I want it to do, but it does show that the SQL side is working fine.


>What if I just did a regular import and based on matching/updating...
That would work if you want to change existing records, but it's not going to give you a history of past records. Also, won't you still need a SQL query to initiate the import?
>>>I would still use an SQL query to get the tables I needed, but on the field mapping section it gives the option of updating records (and adding new). I wouldn't mind "changing" the local records with remote data, as long as the record matching criteria (=) indicated that they were esentially the same record. The difference in dates would indicate that it was a different record, right?

 

by: billmercerPosted on 2006-03-09 at 09:02:14ID: 16146466

> So, I'm guessing that there's just a problem in the way that we're asking it to compare the SQL with the
>Filemaker side.
I'm sure it's just some sort of typo or similar error. To troubleshoot this, just create a calculated field based on this FileMaker calculation...

" SELECT \"orders\".\"Location\", \"orders\".\"Date_modified\" FROM \"orders\"  
  WHERE \"orders\".\"Date_modified\" > " & TimeStampForQuery

Show this calculated field on a layout, and it will show the actual text of the SQL query as it is being submitted to the ODBC driver. Copy and paste it here, and we can figure out where the error is.

>I wouldn't mind "changing" the local records with remote data, as long as the record matching criteria (=)
>indicated that they were esentially the same record. The difference in dates would indicate that it was a
>different record, right?
Only if you used that date as one of your matching criteria.

But if you do this based on a modification date, then ANY change to the record will automatically mean a new record in FileMaker, so effectively, it would be no different than if you just imported new records each time.

 

by: wesbrowningPosted on 2006-03-09 at 09:11:05ID: 16146571

Ok, I figured out the problem. I contacted the SQL driver company and they said my log file looked like this....

SELECT "orders"."Location", "orders"."Date_modified" FROM "orders" † † WHERE "orders"."Date_modified" > {ts '2006-03-01 00:00:00'}

As you can see, right before the WHERE clause there is two † † signs. It turns out this was caused by the carriage returns in SQL calculated text.

I'm getting the results I need now. Thanks for your help, and thanks for sticking in there on this one!

 

by: billmercerPosted on 2006-03-09 at 10:18:26ID: 16147172

That's interesting, normally returns are supposed to be allowable in SQL queries. Maybe it's some sort of cross-platform translation issue or something.

Glad you got it working.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...