Calling a User-Defined Function (UDF) from SQL SELECTID: Q124402 2.50 2.50a 2.50b 2.60 2.60a 3.00 WINDOWS The information in this article applies to:
SUMMARYThis article shows by example how to add functionality to a Structured Query Language (SQL) SELECT command by calling a user-defined function (UDF) from the SELECT.
MORE INFORMATIONAssume that you want to create a query that will produce three or fewer records for each state in the customer table. Using the customer table in the tutorial directory and the code from the "Sample Code" section of this article, you can specify how many records from each state are to be included in the resulting query. The variable max_match is set to 3, but as not all states have 3 or more records, the resulting query won't have 3*49 records. This example will produce 116 records. When max_match is set to 2, the result contains 86 records. When set to 1, the result contains 49 records, which is the same number of records the
Step-by-Step Example1. Create a file that contains the code listed in the "FoxPro 2.x Sample 2. From the FoxPro command line, type "DO main" without the quotation
FoxPro 2.x Sample CodeCLEAR CLEAR ALL SET DEFAULT TO SYS(2004)+"tutorial" match=0 max_match=3 prev_state="None" first_call=.T. SELECT state FROM customer ORDER BY state INTO CURSOR tmp1 SELECT state FROM tmp1 WHERE mycount() FUNCTION mycount DO CASE
CASE (state = prev_state) AND (match < max_match) && Condition 2
OTHERWISE
ENDCASE
RETURN .T.
Visual Foxpro Sample Code
What the Code DoesThe first few lines in the Main program clear the environment and initialize a few global variables to be used in the mycount() UDF. The first SELECT command creates a sorted CURSOR (tmp1) for the second SELECT command to use. The mycount() UDF is called once for each of the records in the tmp1 CURSOR. Each time the UDF returns TRUE, the current record in tmp1 is included in the resulting query. There are four conditions in the UDF: 1. The first condition is only used once. It allows the first record in 2. The second condition allows the second and third records for each state
3. The third condition allows the first record for each new state to be
4. The fourth condition causes the current record in tmp1 to be skipped.
Additional reference words: VFoxWin 3.00 FoxWin 2.50 2.50a 2.50b 2.60 2.60a
KBCategory:
KBSubcategory: FxprgSql
|
Last Reviewed: May 22, 1998 © 2000 Microsoft Corporation. All rights reserved. Terms of Use. |