Dynamic Query Help

Experts,
I've sample tables with sample records as:-
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Entity]') AND type in (N'U'))
DROP TABLE [dbo].[Entity]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EntityOnlyChanges]') AND type in (N'U'))
DROP TABLE [dbo].[EntityOnlyChanges]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Address]') AND type in (N'U'))
DROP TABLE [dbo].[Address]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AddressOnlyChanges]') AND type in (N'U'))
DROP TABLE [dbo].[AddressOnlyChanges]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Claims]') AND type in (N'U'))
DROP TABLE [dbo].[Claims]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ClaimsOnlyChanges]') AND type in (N'U'))
DROP TABLE [dbo].[ClaimsOnlyChanges]
GO
CREATE TABLE [dbo].[Entity]
BatchID INT,
ID INT,
FNAME VARCHAR(10),
LNAME VARCHAR(10),
GENDER VARCHAR(1),
FUNCTION_FLAG VARCHAR(1)
CREATE TABLE [dbo].[EntityOnlyChanges]
BatchID INT,
ID INT,
FNAME VARCHAR(10),
LNAME VARCHAR(10),
GENDER VARCHAR(1),
FUNCTION_FLAG VARCHAR(1)
INSERT INTO [dbo].[Entity] VALUES ( 1, 121, 'Mike', 'Ty', 'F', '' )
INSERT INTO [dbo].[Entity] VALUES ( 1, 222, 'Lance', 'May', 'M', '' )
INSERT INTO [dbo].[Entity] VALUES ( 1, 601, 'Will', 'Portz', 'M', '' )
INSERT INTO [dbo].[Entity] VALUES ( 1, 636, 'Abc', 'XYZ', 'M', '' )
INSERT INTO [dbo].[Entity] VALUES ( 2, 121, 'Mike', 'Ty', 'F', '' )
INSERT INTO [dbo].[Entity] VALUES ( 2, 222, 'Lance', 'May', 'M', '' )
INSERT INTO [dbo].[Entity] VALUES ( 2, 601, 'Will', 'Portz', 'F', '' )
INSERT INTO [dbo].[Entity] VALUES ( 2, 636, 'Abc', 'XYZ', 'M', '' )
CREATE TABLE [dbo].[Address]
BatchID INT,
ID INT,
AID INT,
ADD1 VARCHAR(35),
ST VARCHAR(2),
FUNCTION_FLAG VARCHAR(1)
INSERT INTO [dbo].[Address] VALUES ( 1, 121, 1210, '28th St', 'MO', '' )
INSERT INTO [dbo].[Address] VALUES ( 1, 222, 2220, '56th St', 'IL', '' )
INSERT INTO [dbo].[Address] VALUES ( 1, 222, 2221, '76 Bvld', 'IL', '' )
INSERT INTO [dbo].[Address] VALUES ( 1, 601, 6010, '601 Main Rd', 'NJ', '' )
INSERT INTO [dbo].[Address] VALUES ( 1, 636, 6360, '45th St', 'CA', '' )
INSERT INTO [dbo].[Address] VALUES ( 1, 636, 6361, '5th St', 'CA', '' )
INSERT INTO [dbo].[Address] VALUES ( 2, 121, 1210, '28th St', 'MO', '' )
INSERT INTO [dbo].[Address] VALUES ( 2, 222, 2220, '56th St', 'IL', '' )
INSERT INTO [dbo].[Address] VALUES ( 2, 222, 2221, '86 Bvld', 'IL', '' )
INSERT INTO [dbo].[Address] VALUES ( 2, 601, 6010, '601 Main Rd', 'NJ', '' )
INSERT INTO [dbo].[Address] VALUES ( 2, 636, 6360, '45th St', 'CA', '' )
INSERT INTO [dbo].[Address] VALUES ( 2, 636, 6361, '6th St', 'CA', '' )
CREATE TABLE [dbo].[AddressOnlyChanges]
BatchID INT,
ID INT,
AID INT,
ADD1 VARCHAR(35),
ST VARCHAR(2),
FUNCTION_FLAG VARCHAR(1)
CREATE TABLE [dbo].[Claims]
BatchID INT,
ID INT,
AID INT,
Phone VARCHAR(10),
Ext VARCHAR(5),
FUNCTION_FLAG VARCHAR(1)
INSERT INTO [dbo].[Claims] VALUES ( 2, 121, 1210, '1234567890', '10095', '' )
INSERT INTO [dbo].[Claims] VALUES ( 2, 636, 6360, '5420567890', '14298', '' )
INSERT INTO [dbo].[Claims] VALUES ( 2, 636, 6361, '5558567890', '22232', '' )
INSERT INTO [dbo].[Claims] VALUES ( 1, 601, 6010, '5420151890', '22246', '' )
INSERT INTO [dbo].[Claims] VALUES ( 2, 121, 1210, '1234567890', '15295', '' )
INSERT INTO [dbo].[Claims] VALUES ( 2, 636, 6360, '5420567890', '14298', '' )
INSERT INTO [dbo].[Claims] VALUES ( 2, 636, 6361, '5558567890', '19532', '' )
INSERT INTO [dbo].[Claims] VALUES ( 2, 601, 6010, '5420151890', '15846', '' )
CREATE TABLE [dbo].[ClaimsOnlyChanges]
BatchID INT,
ID INT,
AID INT,
Phone VARCHAR(10),
Ext VARCHAR(5),
FUNCTION_FLAG VARCHAR(1)
SELECT *
FROM [dbo].[Entity]
ORDER BY BatchID, ID
SELECT *
FROM [dbo].[Address]
ORDER BY BatchID, ID
SELECT *
FROM [dbo].[Claims]
ORDER BY BatchID, ID
INSERT INTO [dbo].[EntityOnlyChanges] VALUES ( 2, 601, 'Will', 'Portz', 'F', 'C' )
INSERT INTO [dbo].[AddressOnlyChanges] VALUES ( 2, 222, 2221, '86 Bvld', 'IL', 'C' )
INSERT INTO [dbo].[AddressOnlyChanges] VALUES ( 2, 636, 6361, '6th St', 'CA', 'C' )
INSERT INTO [dbo].[ClaimsOnlyChanges] VALUES ( 2, 121, 1210, '1234567890', '15295', 'C' )
INSERT INTO [dbo].[ClaimsOnlyChanges] VALUES ( 2, 636, 6360, '5420567890', '14298', 'C' )
INSERT INTO [dbo].[ClaimsOnlyChanges] VALUES ( 2, 636, 6361, '5558567890', '19532', 'C' )
SELECT *
FROM [dbo].[EntityOnlyChanges]
ORDER BY BatchID, ID
SELECT *
FROM [dbo].[AddressOnlyChanges]
ORDER BY BatchID, ID
SELECT *
FROM [dbo].[ClaimsOnlyChanges]
ORDER BY BatchID, ID
EXEC [dbo].[procGetChanges_Temp1] 'Entity,Address, Claims ', 'ID', 'AID', 2
SELECT *
FROM [dbo].[EntityOnlyChanges]
ORDER BY CASE WHEN FUNCTION_FLAG = 'C' THEN 1 ELSE 2 END, ID
SELECT *
FROM [dbo].[AddressOnlyChanges]
ORDER BY CASE WHEN FUNCTION_FLAG = 'C' THEN 1 ELSE 2 END, ID
SELECT *
FROM [dbo].[ClaimsOnlyChanges]
ORDER BY CASE WHEN FUNCTION_FLAG = 'C' THEN 1 ELSE 2 END, ID
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Entity]') AND type in (N'U'))
DROP TABLE [dbo].[Entity]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EntityOnlyChanges]') AND type in (N'U'))
DROP TABLE [dbo].[EntityOnlyChanges]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Address]') AND type in (N'U'))
DROP TABLE [dbo].[Address]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AddressOnlyChanges]') AND type in (N'U'))
DROP TABLE [dbo].[AddressOnlyChanges]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Claims]') AND type in (N'U'))
DROP TABLE [dbo].[Claims]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ClaimsOnlyChanges]') AND type in (N'U'))
DROP TABLE [dbo].[ClaimsOnlyChanges]
GO
Stored Procedure to get "Same" (S) values is here,
CREATE PROCEDURE [dbo].[procGetChanges_Temp1]
@TableNames VARCHAR(MAX),
@PrimaryKeyColumn VARCHAR(255),
@PrimaryKeyColumn1 VARCHAR(255),
@LatestIsReadyImportImportBatchID INT
) AS
BEGIN
DECLARE @TblName VARCHAR(MAX) = @TableNames,
@Split CHAR(1) = ',',
@TblList XML
SELECT @TblList = CONVERT(XML,' <root> <s>' + REPLACE(@TblName,@Split,'</s> <s>') + '</s> </root> ')
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 0)) AS ID,
[TablesList] = LTRIM(RTRIM(T.c.value('.','VARCHAR(30)')))
FROM @TblList.nodes('/root/s') T(c)
INSERT INTO [dbo].[EntityOnlyChanges] ( BatchID, ID, FNAME, LNAME, GENDER, FUNCTION_FLAG )
SELECT BatchID, ID, FNAME, LNAME, GENDER, FUNCTION_FLAG
FROM
SELECT BatchID, ID, FNAME, LNAME, GENDER, 'S' AS FUNCTION_FLAG
FROM [dbo].[Entity]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND ID IN
SELECT ID
FROM [dbo].[AddressOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND FUNCTION_FLAG = 'C'
AND ID NOT IN
SELECT ID
FROM [dbo].[EntityOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
UNION ALL
SELECT BatchID, ID, FNAME, LNAME, GENDER, 'S' AS FUNCTION_FLAG
FROM [dbo].[Entity]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND ID IN
SELECT ID
FROM [dbo].[ClaimsOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND FUNCTION_FLAG = 'C'
AND ID NOT IN
SELECT ID
FROM [dbo].[EntityOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
) EntityOnlyChanges
GROUP BY BatchID, ID, FNAME, LNAME, GENDER, FUNCTION_FLAG
ORDER BY BatchID, ID
INSERT INTO [dbo].[AddressOnlyChanges] ( BatchID, ID, AID, ADD1, ST, FUNCTION_FLAG )
SELECT BatchID, ID, AID, ADD1, ST, FUNCTION_FLAG
FROM
SELECT BatchID, ID, AID, ADD1, ST, 'S' AS FUNCTION_FLAG
FROM [dbo].[Address]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND ID IN
SELECT ID
FROM [dbo].[EntityOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND FUNCTION_FLAG = 'C'
AND ID NOT IN
SELECT ID
FROM [dbo].[AddressOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
UNION ALL
SELECT BatchID, ID, AID, ADD1, ST, 'S' AS FUNCTION_FLAG
FROM [dbo].[Address]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND AID IN
SELECT AID
FROM [dbo].[ClaimsOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND FUNCTION_FLAG = 'C'
AND AID NOT IN
SELECT AID
FROM [dbo].[AddressOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
) AddressOnlyChanges
GROUP BY BatchID, ID, AID, ADD1, ST, FUNCTION_FLAG
ORDER BY BatchID, ID
INSERT INTO [dbo].[ClaimsOnlyChanges] ( BatchID, ID, AID, Phone, Ext, FUNCTION_FLAG )
SELECT BatchID, ID, AID, Phone, Ext, FUNCTION_FLAG
FROM
SELECT BatchID, ID, AID, Phone, Ext, 'S' AS FUNCTION_FLAG
FROM [dbo].[Claims]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND ID IN
SELECT ID
FROM [dbo].[EntityOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND FUNCTION_FLAG = 'C'
AND ID NOT IN
SELECT ID
FROM [dbo].[ClaimsOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
UNION ALL
SELECT BatchID, ID, AID, ADD1, ST, 'S' AS FUNCTION_FLAG
FROM [dbo].[Address]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND AID IN
SELECT AID
FROM [dbo].[AddressOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
AND FUNCTION_FLAG = 'C'
AND AID NOT IN
SELECT AID
FROM [dbo].[ClaimsOnlyChanges]
WHERE BatchID = @LatestIsReadyImportImportBatchID
) AddressOnlyChanges
GROUP BY BatchID, ID, AID, Phone, Ext, FUNCTION_FLAG
ORDER BY BatchID, ID
END
GO
I'm able to get my expected result set with the above SP, but I want to make the above SP dynamic so that if number of tables get increase I don't have to modify the SP currently (above) SP is very much static with can handle only 3 tables.
Can anybody please help me out?
Please let me know if you have any questions for me.
Note:-
Entity table - One record per individual
Address table - Each individual can have multiple address
Claims table - If multiple address per individual multiple claims entries as well
Thanks in advance
Regards,
Kumar
Please do let us know your feedback. Thank You - KG, MCTS

I would be very cautious with trying to produce something that is "dynamic" with regards to tables. In a relational database, a table is supposed to model a unique entity with a number of unique attributes. From this perspective, it is unlikely
that the same piece of code would be applicable to two tables execpt by chance.
I did not fully look into what your procedures does, but having more than once tried to generalise code in my career, I have found that it is often non-trivial. It is fairly mechanical exercise to change the table names to parameters and then use dynamic
SQL. But what says that the next set of tables has exactly these columns? Add to this that this procedure already is a bit complex. If you change the code to use dynamic SQL throughout, you increase the complexity further, and thereby you make it more difficult
to maintain.
I think that a better option if you anticipate to write a bunch of procedures of this type is to write program that generates the code. This permits you to make manual tweaks to the code that you are not able to include in your program.
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • Help on performance with dynamic query

    Hi All,
      We are using SQL Server 2008R2. In our one of report we are using Dynamic query and it is taking more time to retrieve the data. to retrieve 32 records it is taking 13-15 secs. In my observation in a table variable, created more than 60 columns. In
    the SP called one more sp with insert statement.
    Please let me know how i can improve performance of the SP.
    I know that i have to provide the SP  for observation but unfortunately I cannot provide the SP. Please guide me how i can achieve this .
    I tried with temp tables by creating indexes on temp tables but i couldn't find improvement in performance. 
    Waiting for valuable replies.

    First of all a "dynamic query" is not "a query" - it is a multitude of them. Some of them may be fast, others may be slow.
    There is of course no way we can give specific suggestions without seeing the code, the table and index definitions etc.
    We can only give the generic suggestions. As for the code, make sure that you are using parameterised SQL and you are not building a complete SQL string with parameters and all. If nothing else, this helps to make the code more readable and maintainable.
    It also protects you against SQL injection. And it also helps to prevent performance issue due to implicit conversion.
    You will need to look at the query plan to see where the bottlenecks may be. You should look at the actual query plan. Note that the thickness of the arrows are more relevant than the percentages you see; the percentages are only estimates, and estimates
    are often off. Next step is to see if you can add indexes to alleviate the situation. You should also analyse if there are problems in the query, for instance indexed columns that are entangled in expression. If you are using views, make sure that you don't
    have views built on top of views etc. This can often result a table appearing multiple times in a query, when one would be enough.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Help! Inaccessible iterator when using dynamic query

    Hi!
    I have a problem retreiving results from a dynamic query into sqlj iterator.
    I consulted the Oracle App Dev Guide and Oracle SQLJ Dev Guide and wrote the following code:
    <PRE>
    package pmServer;
    #sql iterator LocIterator (int id, String name);
    public class pmRISDImpl
    public int GetLocations(...)
    LocIterator locIt;
    String q = "select ID, NAME from PMADM.LOCATIONS";
    #sql
    BEGIN
    open :OUT locIt for :q;
    END;
    </PRE>
    When I try to compile it using tools provided by JDeveloper ver 3.2.2.(Build 915) for JDK 1.2.2 I get error for #sql statement:
    Inaccessible Java type for host item locIt (at position #1): pmServer.LocIterator
    and warning:
    Type pmServer.LocIterator of host item locIt (at position #1) is not permitted in JDBC. This will not be portable.
    Althow the code is identcal to those demonstrated in Oracle document "Oracle8 i
    SQLJ Developers Guide and Reference
    Release 3 (8.1.7)
    July 2000
    Part No. A83723-01" pp 12-67 (PL/SQL in SQLJ for Dynamic SQLDynamicDemo.sqlj). There it looks like
    <PRE>
    private static void dynamicSelectMany(String what_cond)
    throws SQLException {
    System.out.println("dynamic multi-row query on table emp");
    Employees empIter;
    // table/column names cannot be bind args in dynamic PL/SQL, so
    // build up query as Java string
    String query = "select ename, sal from emp " +
    (((what_cond == null) &#0124; &#0124; (what_cond.equals(""))) ? "" :
    (" where " + what_cond)) +
    "order by ename";
    #sql {
    begin
    open :OUT empIter for -- opening ref cursor with dynamic query
    :query;
    -- can have USING clause here if needed
    end;
    while (empIter.next()) {
    System.out.println("Employee " + empIter.ename() +
    " has salary " + empIter.sal() );
    empIter.close();
    </PRE>
    Please guide me what should I do to get it working.
    null

    In the CAST statement the SQLJ runtime must be able to produce an instance of you SQLJ iterator using Java reflection.
    This necessitates that the iterator class must be accessible by public.
    You have two options:
    (1) Declare the iterator public. This requires that you put it in its own file LocIterator.sqlj:
    #sql public iterator LocIterator (int id, String name);
    (2) Declare the iterator as an inner class. In this case you want to make it public static (that is it does not require an instance of the outer class in scope). You might write the following.
    package pmServer;
    public class pmRISDImpl
    #sql public static iterator LocIterator (int id, String name);
    (3) If you are using Oracle 9i you have another option. You can embed dynamic SQL fragments directly in your SQLJ code and do not need to use the CAST:
    public int GetLocations(...)
    LocIterator locIt;
    String q = "PMADM.LOCATIONS";
    #sql locIt = { select ID, NAME from :{q} }; // Note new syntax :{q} for embedding SQL source code
    }

  • Single quote in dynamic query

    Hi all;
    Can u please help me on the following dynamic query code ? I know I am missing the single quote around 2 dates but could not figure out where to put it ! I have tried putting 2 or 3 quotes around 2 bind vars but to no avail.
    Want to create a dynamic query to simulate the the following:
    select
    EMPNO,ENAME,JOB,MGR,HIREDATE from emp where HIREDATE >= to_date('01/01/1981','MM/DD/YYYY') and HIREDATE <= to_date('12/31/1982','MM/DD/YYYY');
    dynamic code:
    declare
    v_q varchar2(4000);
    begin
    v_q :='select EMPNO,ENAME,JOB,MGR,HIREDATE from emp ';
    V_q := V_Q
    || 'where HIREDATE >= '
    || 'to_date(' || :P_DATE1 || ',' ||'''MM/DD/YYYY''' || ' )'
    || 'and HIREDATE <= '
    || 'to_date(' || :P_DATE2 || ',' ||'''MM/DD/YYYY''' || ' )';
    -- end the sql
    v_q := v_q ||';';
    dbms_output.put_line ('V_Q is ' || V_Q);
    end;
    Thanks.
    Zen

    declare
        v_q varchar2(4000);
        v_rec emp%rowtype;
        v_cur sys_refcursor;
    begin
        v_q :='select EMPNO,ENAME,JOB,MGR,HIREDATE from emp ';
        V_q := V_Q  || 'where HIREDATE >= to_date(:P_DATE1,''MM/DD/YYYY'') and HIREDATE <= to_date(:P_DATE2,''MM/DD/YYYY'')';
        dbms_output.put_line ('V_Q is ' || V_Q);
        open v_cur
          for v_q
          using '01/01/1981',
                '12/31/1982';
        loop
          fetch v_cur
            into v_rec.empno,
                 v_rec.ename,
                 v_rec.job,
                 v_rec.mgr,
                 v_rec.hiredate;
          exit when v_cur%notfound;
          dbms_output.put_line('empno = ' || v_rec.empno);
          dbms_output.put_line('ename = ' || v_rec.ename);
          dbms_output.put_line('job = ' || v_rec.job);
          dbms_output.put_line('mgr = ' || v_rec.mgr);
          dbms_output.put_line('hiredate = ' || to_char(v_rec.hiredate,'MM/DD/YYYY'));
          dbms_output.put_line('====================');
        end loop;
        close v_cur;
    end;
    V_Q is select EMPNO,ENAME,JOB,MGR,HIREDATE from emp where HIREDATE >=
    to_date(:P_DATE1,'MM/DD/YYYY') and HIREDATE <= to_date(:P_DATE2,'MM/DD/YYYY')
    empno = 7499
    ename = ALLEN
    job = SALESMAN
    mgr = 7698
    hiredate = 02/20/1981
    ====================
    empno = 7521
    ename = WARD
    job = SALESMAN
    mgr = 7698
    hiredate = 02/22/1981
    ====================
    empno = 7566
    ename = JONES
    job = MANAGER
    mgr = 7839
    hiredate = 04/02/1981
    ====================
    empno = 7654
    ename = MARTIN
    job = SALESMAN
    mgr = 7698
    hiredate = 09/28/1981
    ====================
    empno = 7698
    ename = BLAKE
    job = MANAGER
    mgr = 7839
    hiredate = 05/01/1981
    ====================
    empno = 7782
    ename = CLARK
    job = MANAGER
    mgr = 7839
    hiredate = 06/09/1981
    ====================
    empno = 7839
    ename = KING
    job = PRESIDENT
    mgr =
    hiredate = 11/17/1981
    ====================
    empno = 7844
    ename = TURNER
    job = SALESMAN
    mgr = 7698
    hiredate = 09/08/1981
    ====================
    empno = 7900
    ename = JAMES
    job = CLERK
    mgr = 7698
    hiredate = 12/03/1981
    ====================
    empno = 7902
    ename = FORD
    job = ANALYST
    mgr = 7566
    hiredate = 12/03/1981
    ====================
    empno = 7934
    ename = MILLER
    job = CLERK
    mgr = 7782
    hiredate = 01/23/1982
    ====================
    PL/SQL procedure successfully completed.
    SQL> SY.

  • Dynamic Query to display a page of records at a time

    I need some help creating procedure with a dynamic query that will query a table and pass out a certain number of records (like records 101 - 200 of 20,000). This procedure will receive the column names, table name, where clause, page number and number of records per page. It will then pass back the requested records to be displayed on a PHP page.
    Pseudo Code:
    Select Dynamic_Columns, ROWNUM
    Into Dynamic_Pl_Sql_Table
    From Dynamic_Table
    Where Dynamic_Where_Clause
    Total_Records_Out := Dynamic_PL_Sql_Table.Count
    Modulus := Mod(Total_Records_Out, Total_Records_Per_Page_In)
    Total_Pages_Out := (Total_Records_Out - Modulus) / Total_Records_Per_Page_In
    If Modulus > 0 Then
    Total_Pages_Out + 1
    End If
    Row_Start = Page_Number_In * Total_Records_Per_Page_In
    Row_End = Row_Start + Total_Records_Per_Page_In
    Results_Out = Dynamic_Pl_Sql_Table(Row_Start ... Row_End)
    Any help with this will be appreciated!

    Maybe this will help you
    1) If the Serial is 0 then page break
    2) total_rows gives you total number of rows selected.
    3) you can apply where clause to this and it will give you appropriate records.
    select empno, ename, sal, 
    mod(row_number() over (order by null),5) serial,
    count(*) over () tot_rows from emp ed
         EMPNO ENAME             SAL     SERIAL   TOT_ROWS
          7369 SMITH             800          1         14
          7499 ALLEN            1600          2         14
          7521 WARD             1250          3         14
          7566 JONES            2975          4         14
          7654 MARTIN           1250          0         14
          7698 BLAKE            2850          1         14
          7934 MILLER           1300          2         14
          7788 SCOTT            3000          3         14
          7839 KING             5000          4         14
          7844 TURNER           1500          0         14
          7876 ADAMS            1100          1         14
          7900 JAMES             950          2         14
          7902 FORD             3000          3         14
          7782 CLARK            2450          4         14
    14 rows selected.SS

  • Dynamic query in where clause while looping in an internal table.

    Hi,
    Had a small question : How can i make a dynamic query for the WHERE clause while looping at an internal table.
    i want to implement a dynamic where clause query for the below example.
    it_cfx_col is an internal table and wa_cfx_col is a work area for it_cfx_col
      DATA :
      i_cfx_col TYPE TABLE OF cfx_col,
      wa_cfx_col LIKE LINE OF i_cfx_col.
    DATA : count TYPE i VALUE 0.
    DATA : l_where_clause TYPE string,
             l_where_clause2 TYPE string,
             l_name type string.
    l_name = 'NANDANOM'.
    l_scenario = 'collaboration'.
    LOOP AT it_cfx_col INTO wa_cfx_col
    WHERE CREATED_BY = l_name
    AND SCENARIO = l_scenario.
    count = count + 1.
    some business logic implemented using the work area wa_cfx_col
    endloop.
    Now i want to write a dynamic query for the where clause.
    DATA : count TYPE i VALUE 0.
      DATA : l_where_clause TYPE string,
             l_where_clause2 TYPE string,
             l_name type string.
    l_name = 'NANDANOM'.
    l_scenario = 'collaboration'.
      l_where_clause = 'CREATED_BY = l_name'.
      l_where_clause2 = 'AND SCENARIO = l_scenario'.
    if l_scenario is not initial.
      CONCATENATE  l_where_clause l_where_clause2
      INTO l_where_clause SEPARATED BY space.
    endif.
    LOOP AT i_cfx_col INTO wa_cfx_col
    WHERE (l_where_clause).
    count = count + 1.
    some business logic implemented using the work area wa_cfx_col
    endloop.
    when i compile this i get an error message as { Statement concluding with "...(l_where_clause)" ended unexpectedly}
    Even i changed the initilization of the variable  l_where_clause2 to [ l_where_clause2 = 'AND SCENARIO = l_scenario.'. ]
    added the end of line demarkation ".", but still i got the same error message.
    Is it a limtation in ABAP that i cannot write a dynamic query for the where clause while looping at an internal table?
    Regards,
    om

    Hi savita,
    there in no such 1 limitaion in abap for dynamic query .. i think the  error meassge is only beacuse of your synatx delcartaion.
    >> LOOP AT i_cfx_col INTO wa_cfx_col
       WHERE (l_where_clause).
       count = count + 1.
    some business logic implemented using the work     area    wa_cfx_col
       endloop.
    afted delclarataion also , in the where statement you should specify both the field name and value bname
       LOOP AT i_cfx_col INTO wa_cfx_col
       WHERE l_where_clause = 'CREATED_BY = l_name' .
       count = count + 1.
    hope it helps.
    regads
    priya.

  • Dynamic Query

    Dynamic Query
    When I run the following dynamic query in the stored procedure and try to build the report then I get the following error Rep:1401 Fatal PL/SQL error occured, Ora-00936 Missing expression. When I am generating the report standalone using the following query , everything is working fine but in Stored procedure , it's giving me the above error, pls help.
    create or replace package REP_DELIVERY_LOC_STATISTICS is
    TYPE REP_DELIVERY_LOC_STAT_rec IS RECORD(
    p_coordinating_facility_id sis_education_pgm_session.coordinating_facility_id%TYPE,
    p_PSE_MUNICIPALITY_ID pse_education_pgm_session.PSE_MUNICIPALITY_ID%TYPE,
    p_pse_education_pgm_session_id sis_education_pgm_session.pse_education_pgm_session_id%TYPE,
    p_course_session_id course_session.course_session_id%TYPE);
    TYPE REP_DELIVERY_LOC_STAT_cur IS REF CURSOR RETURN REP_DELIVERY_LOC_STAT_rec;
    Type REP_DELIVERY_LOC_STAT_cur_Dyn is REF CURSOR;
    FUNCTION REP_DELIVERY_LOC_STATISTICS(p_college_id IN pse_education_pgm_session.delivery_institution_id%TYPE,
    p_start_date IN pse_education_pgm_session.session_strt_dte%TYPE,
    p_end_date IN pse_education_pgm_session.session_strt_dte%TYPE,
    p_coord_facility_join IN varchar2) return REP_DELIVERY_LOC_STAT_cur_Dyn;
    end REP_DELIVERY_LOC_STATISTICS;
    create or replace package body REP_DELIVERY_LOC_STATISTICS is
    FUNCTION REP_DELIVERY_LOC_STATISTICS(p_college_id IN pse_education_pgm_session.delivery_institution_id%TYPE,
    p_start_date IN pse_education_pgm_session.session_strt_dte%TYPE,
    p_end_date IN pse_education_pgm_session.session_strt_dte%TYPE,
    p_coord_facility_join varchar2) return REP_DELIVERY_LOC_STAT_cur_Dyn IS
    REP_DELIV_LOC_STAT_CUR_Dyn_Q REP_DELIVERY_LOC_STAT_cur_Dyn;
    BEGIN
    OPEN REP_DELIV_LOC_STAT_CUR_Dyn_Q FOR
    'SELECT distinct
    seps.coordinating_facility_id,
    peps.PSE_MUNICIPALITY_ID,
    seps.pse_education_pgm_session_id,
    cs.course_session_id
    FROM pse_education_pgm_session peps,
    sis_education_pgm_session seps,
    course_session cs,
    facility fac,
    desc_sis_reporting_area depa,
    desc_sis_reporting_type dept,
    pse_education_program pep
    WHERE peps.delivery_institution_id (+) = ' || p_college_id
    || ' and peps.session_strt_dte between ' ||p_start_date||' and ' || p_end_date
    || ' and seps.coordinating_facility_id = fac.facility_id (+)
    and seps.pse_education_pgm_session_id (+) = peps.pse_education_pgm_session_id
    and seps.pse_education_pgm_session_id = cs.pse_education_pgm_session_id (+)
    and pep.pse_education_program_id = peps.pse_education_program_id
    and dept.desc_sis_reporting_area_id = depa.desc_sis_reporting_area_id
    and pep.desc_sis_reporting_type_id = dept.desc_sis_reporting_type_id
    and dept.desc_sis_reporting_area_id = depa.desc_sis_reporting_area_id
    and fac.desc_facility_id in (2,3)' || NVL (p_coord_facility_join, '1=1');
    return REP_DELIV_LOC_STAT_CUR_Dyn_Q;
    END;
    end REP_DELIVERY_LOC_STATISTICS;

    I would sugest to grab a book like
    Inside Microsoft SQL Server 2008 T-SQL Querying (chapter 12 - Graphs, Trees, Hierarchies and Recursive Queries) or
    Joe Celko's Trees and Hierarchies in SQL for Smarties to get familiar with how model hierarchies using SQL.
    What is the meaning of the asterisks in the path?
    Here is a dirty example using the Adjacency List model.
    SET NOCOUNT ON;
    USE tempdb;
    GO
    CREATE TABLE dbo.T1 (
    id int NOT NULL UNIQUE CLUSTERED,
    name varchar(50),
    rootid int NULL
    INSERT INTO dbo.T1 (id,name,rootid)
    SELECT 1, 'animals', NULL
    UNION ALL
    SELECT 2, 'mamal', 1
    UNION ALL
    SELECT 3, 'cephalopod mollusc', 1
    UNION ALL
    SELECT 4, 'salt water fish', 1
    UNION ALL
    SELECT 5, 'fresh water fish', 1
    UNION ALL
    SELECT 6,'whale', 2
    UNION ALL
    SELECT 7,'pirana', 5
    UNION
    SELECT 8,'shark', 4
    UNION
    SELECT 9, 'octopus', 3;
    GO
    WITH Tree AS (
    SELECT
    id, name, rootid,
    CAST('/' + [name] + '/' AS varchar(900)) AS mat_path
    FROM
    dbo.T1
    WHERE
    rootid IS NULL
    UNION ALL
    SELECT
    C.id, C.name, C.rootid, CAST(P.mat_path + C.name + '/' AS varchar(900))
    FROM
    Tree AS P
    INNER JOIN
    dbo.T1 AS C
    ON P.id = C.rootid
    SELECT
    FROM
    Tree
    ORDER BY
    mat_path;
    GO
    DROP TABLE dbo.T1;
    GO
    Excuse my poor knowledge of zoology or animal biology.
    AMB
    Some guidelines for posting questions...
    AYÚDANOS A AYUDARTE, guía básica de consejos para formular preguntas

  • How to create an LOV based on a dynamic query

    Hi,
    Can someone tell me how to query a dynamic query for LOV. On my base page I have a dropdown-box (that will show the table names for searching) and is dynamically populated based on users access e.g. if user A logs in he may see 5 values (these values are basically table names) in a drop down if user B logs in he may see 10 values. I also have two input fields one field a user can enter value and the other field is read only and a torch icon for LOV so the user can search and select values that are populated in the input fields on the base page.
    How can I have my LOV that takes in a value selected in the dropdown and anyvalue entered in one of the input fields and search in the table selected in the dropdown box.
    Basically my LOV should do a search on the table and some search value passed when clicking on the torch icon. So a user can select any table-name in the drop down and my LOV should do a search only on the selected table. Once on the LOV Popup want to have a search field there but it only searched on the table selected in the dropdown on the based page. And the selected value on the LOV Popup page gets populated in fields on the base page.
    Any help is appreciated.
    Thanks

    Hi,
    I have created 4 SQL Based VO's with the following sqls
    SELECT header_id AS ID, to_char(order_number) AS NAME
      FROM oe_order_headers_all
    SELECT party_id AS ID, party_name AS NAME
      FROM hz_parties
    SELECT quote_header_id AS ID,
           (quote_number || CHR (45) || quote_version) AS NAME
      FROM aso_quote_headers
    SELECT sales_lead_id AS ID, to_char(lead_number) AS NAME
      FROM as_sales_leadsI created on LOVRegin and have the following 2 messagestyle items now what do I set in the ViewInstance and View Attribute fields
    srcid
    srcname
    Can you provide some sample code to set ViewUsage and whereclause that I need to put in the controller of LOVRegion.
    Thanks

  • Dynamic Query Doubt

    Hi,
    I need to write a Dynamic Query to get the data from the table by using the Input date parameters.
    LIke,
    SELECT* from table where date_start between to_date('12-14-2004','mm-dd-yyyy') AND
    to_date('12-15-2005','mm-dd-yyyy');
    How can i write the above query in dynamic sql as i will get the two dates as input in my procedure
    Help me in this

    Or more preferably use bind variables with the
    EXECUTE IMMEDIATE as, if the query will be called
    many times, the bind variables will prevent hard
    parsing of the statement each time (i.e. it will be
    quicker to execute).blushadow,
    Yes, the execute immediate using bind variables is better/faster than not using bind variables, but your first example outperforms your second one. This is due to the fact that execute immediate really closes all cursors, and in your first example the cursors are kept open (yes, even though you issue a CLOSE cur_test) in the PL/SQL cursor cache.
    SQL> create table i_links
      2  as
      3  select sysdate - l linkdate from (select level l from dual connect by level <= 10000)
      4  /
    Tabel is aangemaakt.
    SQL> exec dbms_stats.gather_table_stats(user,'I_LINKS')
    PL/SQL-procedure is geslaagd.
    SQL> create or replace procedure test1 (start_date in date, end_date in date) as
      2    CURSOR cur_test IS
      3      SELECT count(*)
      4      FROM   i_links
      5      WHERE  linkdate BETWEEN start_date AND end_date;
      6    v_count NUMBER;
      7  begin
      8    OPEN cur_test;
      9    FETCH cur_test INTO v_count;
    10    CLOSE cur_test;
    11    --DBMS_OUTPUT.PUT_LINE('Count: '||v_count);
    12  end;
    13  /
    Procedure is aangemaakt.
    SQL> create or replace procedure test2 (start_date in date, end_date in date) as
      2    v_count NUMBER;
      3  begin
      4    EXECUTE IMMEDIATE 'SELECT count(*) FROM i_links WHERE linkdate BETWEEN :x1 AND :x2' INTO v_count USING start_date, end_date;
      5    --DBMS_OUTPUT.PUT_LINE('Count: '||v_count);
      6  end;
      7  /
    Procedure is aangemaakt.
    SQL> begin
      2    -- warm up
      3    test1(sysdate-365,sysdate);
      4    test2(sysdate-365,sysdate);
      5    -- begin test
      6    runstats_pkg.rs_start;
      7    for i in 1..1000
      8    loop
      9      test1(sysdate-365,sysdate);
    10    end loop;
    11    runstats_pkg.rs_middle;
    12    for i in 1..1000
    13    loop
    14      test2(sysdate-365,sysdate);
    15    end loop;
    16    runstats_pkg.rs_stop(100);
    17  end;
    18  /
    Run1 draaide in 341 hsecs
    Run2 draaide in 348 hsecs
    Run1 draaide in 97,99% van de tijd
    Naam                                                    Run1      Run2  Verschil
    STAT.session cursor cache hits                             0       998       998
    STAT.opened cursors cumulative                             0     1,000     1,000
    STAT.parse count (total)                                   0     1,000     1,000
    LATCH.shared pool                                      1,047     3,043     1,996
    STAT.recursive calls                                   3,001     1,001    -2,000
    LATCH.library cache pin allocation                         8     2,011     2,003
    LATCH.library cache pin 2,048 6,044 3,996
    LATCH.library cache 2,056 6,060 4,004
    Run1 latches totaal versus run2 -- verschil en percentage
          Run1      Run2  Verschil     Pct
        48,522    60,548    12,026  80.14%
    PL/SQL-procedure is geslaagd.Regards,
    Rob.

  • Question on Dynamic Query Data Source and Form Folders in Oracle Forms 6i

    Hi there -
    I have one interesting requirement in Oracle Forms.
    This is what I wanted to do.
    1. Have a LOV and Go button on Form.
    2. From LOV, I will select a pre-defined custom table and click Go.
    3. Based on the selected custom table, I have to populate the Block (Tabular Format).
    4. User should be able to do update, delete, insert on this block.
    5. User should be able to use the Oracle Form folders functionality (select only necessary column and save views etc. Std folder functionality).
    6. If user selects a different custom table name in the LOV on top, I need to refresh the data from the block based on this new table. Remaining functionality should be as it is (steps 3 to 5).
    You can see here, I am going to have dynamic query data source (Table Name as well as column mapping) on the block. I do not know before hand how many columns the user selected table has!
    This is what I have planned for this so far but I have some major questions before I can move on with this design:
    1. I am going to create a table structure with fixed number of column in form (40 cols assuming that the custom table will not have more that 40 cols). (Kind of limitation but it's okay as of now).
    2. Dynamically populate the block based on the table name selected by the user from LOV. Dynamically change the table column names based on the table selected etc.
    3. Perform insert, update, delete using PL/SQL package.
    So far it looks okay.
    Now my real question is,
    Can user still be able to user "Folders" functionality here? I have never done this kind of development before and I doubt the dynamic column naming, dynamic column data source will really work for "folders"!
    Also, I am not really sure whether user will be able to save these "folder" queries?
    Okay so form experts, can you ppl suggest me if this is really going to work? Are there any better ways to do this?
    Initially I tried to do this in OA Framework but I got stuck at because as per OAF developer guide "I cannot user OAF personalization for dynamic items, regions etc".
    For more info on that thread see this link...
    Re: setUserCustomizable issue!
    Thanks in advance for the help.

    Any suggestion anyone?

  • Dynamic Query in Report Builder

    HI
    I have a doubt:
    I need to receive a parameter in my report and I need this parameter in the query, that means, I need to create a dynamic query depending on the value that I receive in one of the parameters that has my report.
    I tried to use the resource of Searching by Reference Cursor tool, it is a blue circle in the Data Model View of Report Builder.
    When I click this tool, I have an initial code, It is:
    function QR_1RefCurDS return <RefCurType> is
    begin
    end;
    In PL/SQL I tried to create to test and to play, this code:
    Note: If you want to try only to test, it is simple and works:
    create or replace package TEST_REFCURTYPE as
    type refcurtype is ref cursor;
    function TEST_REFCURTYPE (P_DATE_TO nvarchar2) return refcurtype;
    end;
    create or replace package body TEST_REFCURTYPE as
    function TEST_REFCURTYPE (P_DATE_TO nvarchar2)
    return refcurtype is
    refcur refcurtype;
    mysql varchar(1000);
    begin
    If P_DATE_TO is not null then
    mysql := 'select '''|| P_DATE_TO ||''' from dual';
    else
    mysql := 'select sysdate from dual';
    end if;
    open refcur for mysql;
    return refcur;
    end;
    end;
    The problem is to pass this example of code to the function QR_1RefCurDS, I do not have a place to make reference to the type:
    type refcurtype is ref cursor;
    I tested the Unit Program in the Report Builder but it did not work, because all the code I try to write and create, for example in the Event BEFORE REPORT, it opens  Funcion( ) …., and I can not make reference to the type refcurtype inside a Function( ).
    Would you help me please?
    Or there is another way to make a dynamic query in the Report Builder?
    Sorry for my English, I am a Brazilian living in Spain.

    Hi,
    you can use lexical parameters in your queries. Instead of a ":" use in the query before the parameter a "&". Then the parameter stands for a part of the query and not for a value (Bind parameter). In the before report trigger you can set this parameters. They can contain parts of SQL like order or where. Make sure that the default value for this lexical parameters are set to get a valid query.
    SELECT ENAME, &p_column as COL2 FROM EMP &p_order
    and in the trigger something like
    IF :p_which_column = 1 THEN
    :p_column := 'SAL'
    ELSE
    Saludos
    Rainer

  • How to use dynamic query for Result table

    Hello Experts,
    I want to use dynamic query and then display the result in the assignment block.
    Using dynamic query BTQAct and BTQRAct and base on some search criteria i want tofilter and then append the result in the result table of that custom context node, and then it should display the result in the view in UI.
    SO can you please provide me the samplle code on how to use the dynamic query and append in the result table.
    Regards.

    Hi,
    Please find below sample code:
    data:  query         TYPE REF TO cl_crm_bol_dquery_service,
               result        TYPE REF TO if_bol_bo_col.
    DATA: lt_params       TYPE crmt_name_value_pair_tab,        
               lwa_params      TYPE crmt_name_value_pair.             
    query = cl_crm_bol_dquery_service=>get_instance( 'BTQAct' ). " Get instance of dynamic query
    Set general query parameter for maximum number of hits
          lwa_params-name = 'MAX_HITS' .
          lwa_params-value = '50'.
          APPEND lwa_params TO lt_params.
          query->set_query_parameters( it_parameters = lt_params ).
          query->add_selection_param( iv_attr_name = 'OBJECT_ID'
                                                    iv_sign      = 'I'
                                                    iv_option    = 'EQ'
                                                    iv_low       = <lv_objectid>
                                                    iv_high      = '' ). " Set your search criteria. Repeat this code if you have multiple parameters
    "You can find possible search options for a query object in  GENIL_BOL_BROWSER
    result ?= query->get_query_result(  ).   " Get result from your search query
    me->typed_context-> <your result context node>->set_collection( result ). 
    Here you will have to create a context node in your view which would refer to query result object like for BTQAct its BTQRAct                      
    Hope this helps.
    e Regards,
    Bhushan

  • Dynamic query in weblogic 7.0?

    Hi:
    I tried dynamic query in weblogic 7.0 for almost a month but still failed. So I wish someone can help me .
    I used dynamic query in a session bean.
    QueryHome queryHome = (QueryHome) ctx.lookup("java:comp/env/ejb/BooksEJB");
    But this line always returns null for queryHome. I am sure my JNDI for CMP 2.0 BooksEJB is right.
    I also set <enable-dynamic-queries>True</enable-dynamic-queries>
    in descriptor file followed by instructions in bea documentation.
    Thanks !

    Ace:
    Shall I set this parameter in weblogic descriptor file ? If so, how do I set
    ? Thanks for your information here !
    [email protected] (Ace) wrote:
    The parameter for ctx.lookup() is what you have set the JNDI name for
    QueryHome in weblogic.
    ~Ace.
    Cottonxu <[email protected]> wrote in message news:<[email protected]>...
    Hi:
    I tried dynamic query in weblogic 7.0 for almost a month but stillfailed. So I wish someone can help me .
    I used dynamic query in a session bean.
    QueryHome queryHome = (QueryHome) ctx.lookup("java:comp/env/ejb/BooksEJB");
    But this line always returns null for queryHome. I am sure my JNDIfor CMP 2.0 BooksEJB is right.
    I also set <enable-dynamic-queries>True</enable-dynamic-queries>
    in descriptor file followed by instructions in bea documentation.
    Thanks !

  • How to create a dynamic query in which I can vary number of parameters

    I am writing a JDBC connector. I want to write a dynamic query in that. The query should be able to proceed variable number of parameters and also in the where clause the and/or/like parameters I want to place dynamically.
    I can't write store procedures as we just have read only access to Database so I want to do it through query only.
    Please help me out in doing that as I am not able to proceed further without it ...

    Hi,
    Have a luk at :placeholder for IN condition in database adapter

  • Dynamic Querying in ESB

    Hey,
    I am trying to implement dynamic querying using the query by example concept. My requirement is as follows:
    "Say I have 5 inputs , I need to fetch rows from the database using those 5 inputs as a part of my where clause"
    The user input are optional. Hence using the query by example concept I was able to filter rows.
    But the problem is as follows:
    1) I have a "time from" and "a time to" field as user inputs. I need to filter the fetched rows so that time is in that time range only. I do not know how to implement this also along with the above concept as there is no place for a where clause.
    Any help/suggestions would be appreciated.
    Thanks

    I tried applying the patch, but it gives the following error:
    OPatch detects your platform as 207 while this patch 6133448 supports platforms:
    0 (Generic Platform)
    This patch is not suitable for this operating system.
    Please contact support for the correct patch.
    ERROR: OPatch failed during pre-reqs check.
    OPatch returns with error code = 150
    I downloaded for the OS I am on, but always the generic patch downloads; i guess this generic one should work for all platforms. Opatch version is 1.0.0.0.56.

Maybe you are looking for

  • Run_report_object_proc does not compile

    Hi all, I am trying to call reports from forms menu. I have tried the generic solution provided by oracle whitepaper of March 2004 using Run_Report_Object_Proc. The problem is that the procedure fails to compile. The error generated is PLS-00201 iden

  • Computer was wiped, how do i re-establish my ipod library with my new one?

    Hello anybody out there... Due to a couple growing problems with my computer, i had to have it completely wiped and everything deleted off of it. I reinstalled itunes and have everything working fine again, but I'm not sure how to add the new songs i

  • Assigning a date countdown to fields in a pop up menu

    Hi everybody. I would be very grateful for some help.  I need to create a spreadsheet using Apple Numbers where I can insert the date of an inspection, select either 2 years, 1 year, 6 months or three months from a pop up menu, and have a cell that c

  • All Day Event in 5.1

    Can any one help me in setting an all day event. Am using wcap to create an all day event. if i set the start date as 20070824T020000Z and isAllDay to 1.The event get scheduled on 23 of aug.Do i need to pass any other parameter along with isAllDay pa

  • Format and precision and rounding?

    I have a vi I have attached and it is giving me fits. I am trying to create a number generator which will automatically figure out the number of turns I need to turn. I have plugged in default numbers for testing purposes. My results appear to be tru