Output query and alert if there is a duplicate between 2 tables

I have 2 tables MembTableA and MembTableB. If a MemberNumber exists on both tables I want to somehow put an alert in my coldfusion output (I have an example "CFIF" in my code below) - and only show the 1 result from MemberTableA. Below is my query and output - can someone assist?
Query in CFC
SELECT     dbo.MembTableA.MemberNumber, dbo.MembTableA.StatusCode, dbo.membTableB.Status
FROM         dbo.MembTableA LEFT OUTER JOIN
                      dbo.membTableB ON dbo.MembTableA.MemberNumber = dbo.membTableB.MemberNumber
                                Where dbo.MembTableA.status IS NULL
                                AND (dbo.MembTableA.StatusCode) = <cfqueryparam value="555" cfsqltype="cf_sql_varchar">
                                or dbo.membTableB.Status = <cfqueryparam value="999" cfsqltype="cf_sql_varchar">
Output code on page
<cfinvoke component=.....
          method="MemberNumberLst"
          returnvariable="MemberNumberLst">
<table>
                <tr>
                  <th>Member Number</th>
                  <th>Status Code</th>
                </tr>
<cfoutput query="MemberNumberLst">
                <tr>
                  <cfif MemberNumberLst.MemberNumber is on both tables ..... >
                  <td>#MemberNumber# **on both tables**</td>
                  <cfelse>
                  <td>#MemberNumber#</td>
                  </cfif>
                  <td>#StatusCode#</td>
                </tr>    
</cfoutput>
</table>

earwig75,
Since you are doing a left outer join, if there is a matching MemberNumber in MembTableB, you just need to check if the dbo.membTableB.MemberNumber column is not blank.  You'll need to add the dbo.MembTableB.MemberNumber column to your SELECT statement.  However, because ColdFusion's query results don't carry fully qualified column names (i.e. dbo.membTableA.MemberNumber and dbo.membTableB.MemberNumber will both be listed as MemberNumber), you will have to use an alias on that column.  Also, if you use aliases on table names, it will simplify the rest of your query.  Here's a cleaner version:
SELECT     tblA.MemberNumber, tblA.StatusCode, tblB.Status, tblB.MemberNumber as MemberNumberB
FROM         dbo.MembTableA  AS tblA LEFT OUTER JOIN
                      dbo.membTableB AS tblB ON tblA.MemberNumber = tblB.MemberNumber
                                Where tblA.status IS NULL
                                AND (tblA.StatusCode) = <cfqueryparam value="555" cfsqltype="cf_sql_varchar">
                                or tblB.Status = <cfqueryparam value="999" cfsqltype="cf_sql_varchar">
Will MemberNumber always appear in MembTableA and only sometimes in MembTableB?  If so, then the modified query should work.  If the number might appear in MembTableA sometimes, or might appear in MembTableB sometimes, then the query probably needs to be redesigned.  If MemberNumber will always appear in MembTableA, your <cfif> could then look like this:
<cfif MemberNumberLst.MemberNumberB <> ''>
Also, you might want to check the location of the parenthesis in your WHERE clause.  AND operators take precedence over OR operators, so this query is going to either find records where both the tblA.status is null AND tblA.StatusCode equals '555', or records where tblB.Status equals '999'.  Is this precisely what you want?
HTH,
-Carl V.

Similar Messages

  • Working with a complex query and trying to get rid of duplicates

    I'm working with the following complex query, and I need to
    select vin, number, year, make, model, and state from
    2007 vehicles in certain models, vin types
    2006 vehicles in certain models, vin types
    Is there a more efficient way to write this than how I've been writing it?:
    select distinct vehicle.vin VIN, unit.STATION_ID STID, unit.EMBEDDED_AREA_CODE||unit.EMBEDDED_PREFIX||lpad(unit.EMBEDDED_RON,4,0)
    MIN, unit.AUTHENTICATION_ID AUTHCODE, vehicle.user_veh_desc, veh_model.VEH_MODEL_DESC MODEL, veh_model.VEH_MANUF_YEAR YEAR, acct_veh.STATE STATE
    from vehicle
    inner join veh_unit on vehicle.vehicle_sak=veh_unit.vehicle_sak
    inner join unit on veh_unit.unit_sak=unit.unit_sak
    inner join vdu_profile on vdu_profile.vehicle_sak=vehicle.vehicle_sak
    inner join vdu_profile_program on vdu_profile_program.VDU_PROFILE_SAK=vdu_profile.VDU_PROFILE_SAK
    inner join veh_model on vehicle.VEH_MODEL = veh_model.VEH_MODEL
    inner join acct_veh on acct_veh.VEHICLE_SAK = vehicle.VEHICLE_SAK
    and vehicle.user_veh_desc like ('%2007%')
    AND unit.unit_gen_id >= 36
    AND vdu_profile_program.VDU_PROGRAM_SAK = 3
    and vdu_profile_program.PREFERENCE_VALUE = 'Y'
    and acct_veh.STATE in ('MN','ND','IA')
    AND (veh_model.VEH_MODEL_DESC like ('%Vehicle2%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle3%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle5%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle6%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle7%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle8%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle9%'))
    and ACCT_VEH.ACCT_VEH_STATUS_ID = 'A'
    and (vehicle.vin like ('_______3_________')
    or vehicle.vin like ('_______W_________')
    or vehicle.vin like ('_______K_________')
    or vehicle.vin like ('_______0_________'))
    UNION
    select distinct vehicle.vin VIN, unit.STATION_ID STID, unit.EMBEDDED_AREA_CODE||unit.EMBEDDED_PREFIX||lpad(unit.EMBEDDED_RON,4,0)
    MIN, unit.AUTHENTICATION_ID AUTHCODE, vehicle.user_veh_desc, veh_model.VEH_MODEL_DESC MODEL, veh_model.VEH_MANUF_YEAR YEAR, acct_veh.STATE STATE
    from vehicle
    inner join veh_unit on vehicle.vehicle_sak=veh_unit.vehicle_sak
    inner join unit on veh_unit.unit_sak=unit.unit_sak
    inner join vdu_profile on vdu_profile.vehicle_sak=vehicle.vehicle_sak
    inner join vdu_profile_program on vdu_profile_program.VDU_PROFILE_SAK=vdu_profile.VDU_PROFILE_SAK
    inner join veh_model on vehicle.VEH_MODEL = veh_model.VEH_MODEL
    inner join acct_veh on acct_veh.VEHICLE_SAK = vehicle.VEHICLE_SAK
    and vehicle.user_veh_desc like ('%2006%')
    AND unit.unit_gen_id >= 36
    AND vdu_profile_program.VDU_PROGRAM_SAK = 3
    and vdu_profile_program.PREFERENCE_VALUE = 'Y'
    and acct_veh.STATE in ('MN','ND','IA')
    AND (veh_model.VEH_MODEL_DESC like ('%Vehicle1%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle2%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle3%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle4%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle5%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle6%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle7%'))
    and ACCT_VEH.ACCT_VEH_STATUS_ID = 'A'
    and (vehicle.vin like ('_______Z_________')
    or vehicle.vin like ('_______K_________'))

    I am not sure how many rows you have in the tables but I am assuming that there would be performance benefits in performing the query only once. You can combine similar coding and use an OR condition for the parts that are different. I left the 'K' vin comparison in both years for readability.
    I was not able to fully test my code but I believe that it will work as is. I hope it helps. If you are happier with the UNION you may want to investigate the WITH clause as you can query a subset of data twice, rather than the full data set.
    -- Common code 
    SELECT DISTINCT
       vehicle.vin,
       unit.station_id stid,
       unit.embedded_area_code || unit.embedded_prefix || LPAD (unit.embedded_ron, 4, 0) MIN,
       unit.authentication_id authcode,
       vehicle.user_veh_desc,
       veh_model.veh_model_desc model,
       veh_model.veh_manuf_year YEAR,
       acct_veh.state
    FROM vehicle
    INNER JOIN veh_unit           
       ON vehicle.vehicle_sak = veh_unit.vehicle_sak
    INNER JOIN unit               
       ON veh_unit.unit_sak = unit.unit_sak
    INNER JOIN vdu_profile        
       ON vdu_profile.vehicle_sak = vehicle.vehicle_sak
    INNER JOIN vdu_profile_program
       ON vdu_profile_program.vdu_profile_sak = vdu_profile.vdu_profile_sak
    INNER JOIN veh_model          
       ON vehicle.veh_model = veh_model.veh_model
    INNER JOIN acct_veh           
       ON acct_veh.vehicle_sak = vehicle.vehicle_sak     
    AND unit.unit_gen_id >= 36
    AND vdu_profile_program.vdu_program_sak = 3
    AND vdu_profile_program.preference_value = 'Y'
    AND acct_veh.state IN ('MN', 'ND', 'IA')
    AND acct_veh.acct_veh_status_id = 'A'
    AND
    -- Annual code
          (   -- 2006 conditions 
          AND vehicle.user_veh_desc LIKE ('%2007%')
          AND regexp_like(veh_model.veh_model_desc, 'Vehicle[2356789]')
          AND regexp_like(vehicle.vin, '_{7}[3WK0]_{9}')           
       OR
          (   -- 2007 conditions 
          AND vehicle.user_veh_desc LIKE ('%2006%')
          AND regexp_like(veh_model.veh_model_desc, 'Vehicle[1234567]')
          AND regexp_like(vehicle.vin, '_{7}[ZK]_{9}')
       ).

  • User Defined Query and Alerts

    Hello guys, I need to set up an alert that happens whenever a Sales Order or Purchase Order is added. I am happy with the alerts procedure but I cannot set up a query.
    Can anyone please help me set up queries that simply mean 'when SO added' and 'when PO added'?
    Many thanks

    OK Groovy - really glad you are following up on this.  Many financial folks like to have this kind of review (especially when they first get onto SAP B1) since it gives them a comfort level of being able to see what is done.
    Good time for you to take a look at the Query Generator and learn a bit of a new skill (PATH: Reports > Query Generator)!  Once you get the hang of it, you can be a real whiz!
    Here is the exact SQL used in their Alert Messaging System.  Type this in exactly as you see it below in the Demo or Test System just to try it out and get a hang of it...
    <b>SELECT
    T0.DocNum AS 'Doc Num',
    T0.UserSign AS 'User ID',
    T0.DocStatus AS 'Doc Status',
    T0.DocDate AS 'Post Date',
    FROM ORDR T0
    WHERE T0.DocStatus = 'O'
    ORDER BY T0.DocNum DESC</b>
    A few comments - the DocNum and UserSign fileds display the famous golden 'drill down' arrows which allow the person to take a look at the document and whoever process the transaction.
    An added bonus is that you can use this exact SQL to query many different tables and use them as their own individual alerts (for example, just substitute ORIN for ORDR and the system will display the AR Credit Memo - all the field names are the same!).
    A WORD OF CAUTION:  Remember this SQL is picking up orders with the status of 'O(pen)'.  It is very important how often you run this Alert Message because it might not report all orders created depending upon the time between order creation and SQL running to generate the alert.  Consider the following scenario: A firm has the alert come up weekly on Friday.  Monday a person creates an order 123, the warehouse ships on Tuesday.  Home office bills the order and closes it on Thursday.  When the alert message is generatedon FRIDAY, 123 will NOT be in the list since it now has a status of 'C(losed)'.  That scenario requires different 'WHERE' selection criteria dealing with dates...
    Good luck - Zal

  • Is there a DIRECT link between SD schedule lines and delivery lines?

    Is there a direct link (db table) between schedule lines on a sales order (VBEP) and the delivery lines (LIPS)? 
    Is there a function module to retrieve the data?
    Example-
    One order line with 3 schedule lines.
    Each schedule line is for 2 units (total of 6 units).
    Three deliveries made.  1st is for 2 units, 2nd is for 1 unit (backorder), 3rd is for 3 units.
    You can use document flow (table VBFA) or examine the SD document in the delivery line (LIPS) and link the delivery line to the order line.  The schedule line already references the order line.
    I am using math to decrement the schedule lines used and make the link between VBEP and LIPS.  It works fine.  I need four records back....
    1st schedule line for 2 units uses delivery 123
    2nd schedule line for 1 unit (partial) uses delivery 124
    2nd schedule line for 1 unit (partial) uses delivery 125
    3rd schedule line for 2 units uses delivery 125
    Like I said, it works. Just wondering if I missed a more direct link.

    As far as Db link is concern , I don’t remember exactly , but 3 years before I had written a report which see Sales order schedule lines and devilry note lines against sales order.  If you see process wise…. when ever you create PO ( production order you assign some qty using 101 movement type .. and against production order you also give sales order . When you do delivery ( run seclude run ) it delivers against that material number , its movement is 601 ...
    but I remember there’s a link between these tables, VBAP,VBFA AND VBEP , LIPS ...  against every sales order you can see sales invoice ( VBRP,VBRK) and you can also see your delivery note number in document flow .
    I hope this’ll give you some guide line, as right now I can not tell you the exact business process but I remember I written a report in SD 4 years before , in which they required Delivery against production order and sales order ... One more thing you also have production order reference on delivery item number. ( field :Empst ) . I think in my project they were maintaining this field .
    Thanks

  • How to provide joins between oracle tables and sql server tables

    Hi,
    I have a requirement that i need to generate a report form two different data base. i.e Oracle and Sql Server.
    how to provide joins between oracle tables and sql server tables ? Any help on this
    Regards,
    Malli

    user10675696 wrote:
    I have a requirement that i need to generate a report form two different data base. i.e Oracle and Sql Server. Bad idea most times. Heterogeneous joins do not exactly scale and performance can be severely degraded by network speed and b/w availability. And there is nothing you can do in the application and database layers to address performance issue at the network level in this case - your code's performance is simply at the mercy of network performance. With a single glaring fact - network performance is continually degrading. All the time. Always. Until it is upgraded. When the performance degradation starts all over again.
    If the tables are not small (few 1000 rows each) and row volumes static, I would not consider doing a heterogeneous join. Instead I would rather go for a materialised view on the Oracle side, use a proper table and index structure, and do a local database join.

  • What is the Relation between System Tables and FND Table?

    Hi,
    I have two LOV's. First one is Module Name. Here I will select Module Name as GL, AP, AR.... In the second LOV it should populate all the API's available in the module. I tried with the following tablesFND_APPLICATION AND ALL_SOURCES. But there is no relation between these tables.
    Can anyone suggest me..
    Please help me out.
    Thanks in Advance,
    Sateesh

    Hi,
    I have two LOV's. First one is Module Name. Here I will select Module Name as GL, AP, AR.... In the second LOV it should populate all the API's available in the module. I tried with the following tablesFND_APPLICATION AND ALL_SOURCES. But there is no relation between these tables.
    Can anyone suggest me..
    Please help me out.
    Thanks in Advance,
    Sateesh

  • Is there a way to exclude specific calendars from Notifications and alerts?

    I have 4 calendars:  1 Exchange and 1 Yahoo that includes 2 shared calendars (wife and MIL).  I activate the Yahoo calendars only when I need them and do not need any yahoo reminders at all.  When I swipe down the Notifications page, it includes all four calendars including the shared Yahoo calendars. What's worse, I get alerts from all four calendars. 
    I only want Exchange alerts and notifications. Is there a way to exclude the Yahoo calendars from Notifications and alerts?
    Right now, the only way I can eliminate them is by deactivating the Yahoo account in Settings/Mail, Contacts, Calendars.

    Is there a way to only choose specific contacts from an existing group and add to a new group? 
     I mean there has be a faster way than typing everybody by hand..

  • Bad query plan for self-referencing CTE view query and variable in WHERE clause. Is there way out or this is SQL Server defect?

    Please help. Thank you for your time and expertise.
    Prerequisites: sql query needs to be a view. Real view is more than recursion. It computes location path,  is used in JOINs and returns this path.
    Problem: no matter what I tried, sql server does not produce 'index seek' when using variable but does with literal.
    See full reproduction code below.
    I expect that query SELECT lcCode FROM dbo.vwLocationCodes l WHERE l.lcID = @lcID will seek UNIQUE index but it does not.
    I tried these:
    1. Changing UX and/or PK to be CLUSTERED.
    2. query OPTION(RECOMPILE)
    3. FORCESEEK on view
    4. SQL Server 2012/2014
    5. Wrap it into function and CROSS APPLY. On large outer number of rows this just dies, no solution
    but to no avail. This smells like a bug in SQL Server. I am seeking your confirmation.
    I am thinking it is a bug as variable value is high-cardinality, 1, and query is against unique key. This must produce single seek, depending if clustered or nonclustred index is unique
    Thanks
    Vladimir
    use tempdb
    BEGIN TRAN
    -- setup definition
    CREATE TABLE dbo.LocationHierarchy(
    lcID int NOT NULL ,
    lcHID hierarchyid NOT NULL,
    lcCode nvarchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    lcHIDParent AS lcHID.GetAncestor(1) PERSISTED,
    CONSTRAINT PK_LocationHierarchy_lcID PRIMARY KEY NONCLUSTERED (lcID ASC),
    CONSTRAINT UX_LocationHierarchy_pltID_lcHID UNIQUE CLUSTERED (lcHID ASC)
    -- add some data
    INSERT INTO dbo.LocationHierarchy
    VALUES
    (1, '/', 'A')
    ,(2, '/1/', 'B')
    ,(3, '/1/1/', 'C')
    ,(4, '/1/1/1/', 'D')
    --DROP VIEW dbo.vwLocationCodes
    GO
    CREATE VIEW dbo.vwLocationCodes
    AS
    WITH ru AS
    SELECT
    lh.lcID
    ,lh.lcCode
    ,lh.lcHID
    ,CAST('/' + lh.lcCode + '/' as varchar(8000)) as LocationPath
    -- to support recursion
    ,lh.lcHIDParent
    FROM dbo.LocationHierarchy lh
    UNION ALL
    SELECT
    ru.lcID
    ,ru.lcCode
    ,ru.lcHID
    ,CAST('/' + lh.lcCode + ru.LocationPath as varchar(8000)) as LocationPath
    ,lh.lcHIDParent
    FROM dbo.LocationHierarchy lh
    JOIN ru ON ru.lcHIDParent = lh.lcHID
    SELECT
    lh.lcID
    ,lh.lcCode
    ,lh.LocationPath
    ,lh.lcHID
    FROM ru lh
    WHERE lh.lcHIDParent IS NULL
    GO
    -- get data via view
    SELECT
    CONCAT(SPACE(l.lcHID.GetLevel() * 4), lcCode) as LocationIndented
    FROM dbo.vwLocationCodes l
    ORDER BY lcHID
    GO
    SET SHOWPLAN_XML ON
    GO
    DECLARE @lcID int = 2
    -- I believe this produces bad plan and is defect in SQL Server optimizer.
    -- variable value cardinality is 1 and SQL Server should know that. Optiomal plan is to do index seek with key lookup.
    -- This does not happen.
    SELECT lcCode FROM dbo.vwLocationCodes l WHERE l.lcID = @lcID -- bad plan
    -- this is a plan I expect.
    SELECT lcCode FROM dbo.vwLocationCodes l WHERE l.lcID = 2 -- good plan
    -- I reviewed these but I need a view here, can't be SP
    -- http://sqlblogcasts.com/blogs/tonyrogerson/archive/2008/05/17/non-recursive-common-table-expressions-performance-sucks-1-cte-self-join-cte-sub-query-inline-expansion.aspx
    -- http://social.msdn.microsoft.com/Forums/sqlserver/en-US/22d2d580-0ff8-4a9b-b0d0-e6a8345062df/issue-with-select-using-a-recursive-cte-and-parameterizing-the-query?forum=transactsql
    GO
    SET SHOWPLAN_XML OFF
    GO
    ROLLBACK
    Vladimir Moldovanenko

    Here is more... note that I am creating table Items and these can be in Locations.
    I am trying LEFT JOIN and OUTER APLLY to 'bend' query into NESTED LOOP and SEEK. There has to be nested loop, 2 rows against 4. But SQL Server fails to generate optimal plan with SEEK. Even RECOMPILE does not help
    use tempdb
    BEGIN TRAN
    -- setup definition
    CREATE TABLE dbo.LocationHierarchy(
    lcID int NOT NULL ,
    lcHID hierarchyid NOT NULL,
    lcCode nvarchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    lcHIDParent AS lcHID.GetAncestor(1) PERSISTED,
    CONSTRAINT PK_LocationHierarchy_lcID PRIMARY KEY NONCLUSTERED (lcID ASC),
    CONSTRAINT UX_LocationHierarchy_pltID_lcHID UNIQUE CLUSTERED (lcHID ASC)
    -- add some data
    INSERT INTO dbo.LocationHierarchy
    VALUES
    (1, '/', 'A')
    ,(2, '/1/', 'B')
    ,(3, '/1/1/', 'C')
    ,(4, '/1/1/1/', 'D')
    --DROP VIEW dbo.vwLocationCodes
    GO
    --DECLARE @Count int = 10;
    --WITH L0 AS (SELECT N FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N (N))-- 10 rows
    --,L1 AS (SELECT n1.N FROM L0 n1 CROSS JOIN L0 n2) -- 100 rows
    --,L2 AS (SELECT n1.N FROM L1 n1 CROSS JOIN L1 n2) -- 10,000 rows
    --,L3 AS (SELECT n1.N FROM L2 n1 CROSS JOIN L2 n2) -- 100,000,000 rows
    --,x AS
    -- SELECT TOP (ISNULL(@Count, 0))
    -- ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as Number
    -- FROM L3 n1
    --SELECT Number as itmID, NTILE(4)OVER(ORDER BY Number) as lcID
    --INTO dbo.Items
    --FROM x
    ----ORDER BY n1.N
    --ALTER TABLE dbo.Items ALTER COLUMN itmID INT NOT NULL
    --ALTER TABLE dbo.Items ADD CONSTRAINT PK PRIMARY KEY CLUSTERED (itmID)
    CREATE TABLE dbo.Items (itmID int NOT NULL PRIMARY KEY, lcID int NOT NULL)
    INSERT INTO dbo.items
    VALUES(1, 1)
    ,(2, 3)
    GO
    CREATE VIEW dbo.vwLocationCodes
    AS
    WITH ru AS
    SELECT
    lh.lcID
    ,lh.lcCode
    ,lh.lcHID
    ,CAST('/' + lh.lcCode + '/' as varchar(8000)) as LocationPath
    -- to support recursion
    ,lh.lcHIDParent
    FROM dbo.LocationHierarchy lh
    UNION ALL
    SELECT
    ru.lcID
    ,ru.lcCode
    ,ru.lcHID
    ,CAST('/' + lh.lcCode + ru.LocationPath as varchar(8000)) as LocationPath
    ,lh.lcHIDParent
    FROM dbo.LocationHierarchy lh
    JOIN ru ON ru.lcHIDParent = lh.lcHID
    SELECT
    lh.lcID
    ,lh.lcCode
    ,lh.LocationPath
    ,lh.lcHID
    FROM ru lh
    WHERE lh.lcHIDParent IS NULL
    GO
    -- get data via view
    SELECT
    CONCAT(SPACE(l.lcHID.GetLevel() * 4), lcCode) as LocationIndented
    FROM dbo.vwLocationCodes l
    ORDER BY lcHID
    GO
    --SET SHOWPLAN_XML ON
    GO
    DECLARE @lcID int = 2
    -- I believe this produces bad plan and is defect in SQL Server optimizer.
    -- variable value cardinality is 1 and SQL Server should know that. Optiomal plan is to do index seek with key lookup.
    -- This does not happen.
    SELECT lcCode FROM dbo.vwLocationCodes l WHERE l.lcID = @lcID-- OPTION(RECOMPILE) -- bad plan
    -- this is a plan I expect.
    SELECT lcCode FROM dbo.vwLocationCodes l WHERE l.lcID = 2 -- good plan
    SELECT *
    FROM dbo.Items itm
    LEFT JOIN dbo.vwLocationCodes l ON l.lcID = itm.lcID
    OPTION(RECOMPILE)
    SELECT *
    FROM dbo.Items itm
    OUTER APPLY
    SELECT *
    FROM dbo.vwLocationCodes l
    WHERE l.lcID = itm.lcID
    ) l
    -- I reviewed these but I need a view here, can't be SP
    -- http://sqlblogcasts.com/blogs/tonyrogerson/archive/2008/05/17/non-recursive-common-table-expressions-performance-sucks-1-cte-self-join-cte-sub-query-inline-expansion.aspx
    -- http://social.msdn.microsoft.com/Forums/sqlserver/en-US/22d2d580-0ff8-4a9b-b0d0-e6a8345062df/issue-with-select-using-a-recursive-cte-and-parameterizing-the-query?forum=transactsql
    GO
    --SET SHOWPLAN_XML OFF
    GO
    ROLLBACK
    Vladimir Moldovanenko

  • Rows to columns/Transpose the records Query and Display output

    hi ,
    can anyone help me query this and transpose it to this format?
    i am still a beginner in sql.
    thanks for help!
    Rows to columns/Transpose the records Query and Display output
    id     startdate     endate                    
    1111     1/2/2001     11/3/2001                    
    1111     2/5/2002     4/3/2002                    
    1111     2/6/2000     2/5/2001                    
    3333     5/2/2003     11/3/2003                    
    3333     6/2/2003     12/3/2003                    
    3333     2/6/2005     2/5/2005                    
    desired output     
    id     startdate1     endate1     startdate2     endate2     startdate3     endate3
    1111     1/2/2001     11/3/2001     2/5/2002     4/3/2002     2/6/2000     2/5/2001
    3333     5/2/2003     11/3/2003     6/2/2003     12/3/2003     2/6/2005     2/5/2005

    Have you only 3 dates for each id ?
    So, try :
    SQL> l
      1  with tbl as
      2  (select 1111 as id, to_date('01/02/2001','DD/MM/YYYY') startdate, to_date('11/03/2001','DD/MM/YYYY') enddate from dual union all
      3  select 1111 as id, to_date('02/05/2002','DD/MM/YYYY') startdate, to_date('04/03/2002','DD/MM/YYYY') enddate from dual union all
      4  select 1111 as id, to_date('02/06/2000','DD/MM/YYYY') startdate, to_date('02/05/2001','DD/MM/YYYY') enddate from dual union all
      5  select 3333 as id, to_date('05/02/2003','DD/MM/YYYY') startdate, to_date('11/03/2003','DD/MM/YYYY') enddate from dual union all
      6  select 3333 as id, to_date('06/02/2003','DD/MM/YYYY') startdate, to_date('12/03/2003','DD/MM/YYYY') enddate from dual union all
      7  select 3333 as id, to_date('02/06/2005','DD/MM/YYYY') startdate, to_date('02/05/2005','DD/MM/YYYY') enddate from dual )
      8  select id, max(decode(dr,1,startdate)) start1,
      9             max(decode(dr,1,enddate)) end1,
    10             max(decode(dr,2,startdate)) start2,
    11             max(decode(dr,2,enddate)) end2,
    12             max(decode(dr,3,startdate)) start3,
    13             max(decode(dr,3,enddate)) end3
    14  from (select id, startdate,enddate, dense_rank() over (partition by id order by startdate) dr from tbl)
    15* group by id
    SQL> /
                                                    ID START1   END1     START2   END2     START3   END3
                                                  1111 02/06/00 02/05/01 01/02/01 11/03/01 02/05/02 04/03/02
                                                  3333 05/02/03 11/03/03 06/02/03 12/03/03 02/06/05 02/05/05
    SQL> HTH,
    Nicolas.

  • There are no functions containing returntype = 'query' and access!

    Hi there
    I am trying to add a recordset after defining a datasource and I keep getting the error when I do a CFC query search
    there are no functions containing returntype = 'query' and access!. I have attached an image to show the error messag I get.
    Can someone help me fix this? my datasource shows up as correctly configured in cold fusion and the mysql database is well configured as well.

    okay, adding another function to the CFC and saving it makes
    it suddenly, magically visible to the function invocation window?
    I don't understand.

  • How to replace a dates on a SQL query on Visual Studio (and get the query to work in there in the first place)?

    Morning all,
    I've just been assigned a report-related project but I have not created much of anything in C# or .Net before!
    I was wondering if someone could help me get started. Here are the specifications:
    Basically, I am to create an automated report application. I have the query and I will include it further down
    in this post. The page is to have a couple blanks to specify the Start Date and End Date and replace those dates in the query, and generate the report. What I need some help on is how to make the SQL query work in the application which I will connect to the
    intended database to generate the report (basic I know, but I'm new at this) on Visual Studio 2010. I also need some help on programming the Start Date blank and End Date blank so that what the user types in for those blanks will replace the date fields in
    the SQL query, then generate the report with the new dates. 
    I appreciate the help!
    The SQL query and what the dates are replacing:
    select 
    PTH.INST_ID ,
    PTH.EMPLOYEE_ID,
    DBH.HR_DEDUCTION_AND_BENEFITS_CODE,
    replace(DB.DESCRIPTION,',',''),
    DB.WITHHOLDING_LIABILITY_ACCOUNT_MASK,
    DBH.HR_DEDUCTION_AND_BENEFITS_ID,
    DBH.CHECK_DATE,
    DBH.CHECK_NO,
    DBH.FIN_INST_ACCT_ID,
    replace(replace (DBH.COMMENT,CHAR(10),' '),CHAR(13),' '),
    DBH.HR_DEDUCTION_AND_BENEFIT_CYCLE_CODE,
    DBH.LENGTH,
    DBH.EMPLOYEE_COMPUTED_AMOUNT,
    DBH.EMPLOYEE_BANK_ROUTING_NUMBER,
    DBH.EMPLOYEE_ACCOUNT_TYPE,
    DBH.EMPLOYEE_ACCOUNT_NUMBER,
    DBH.EMPLOYER_COMPUTED_AMOUNT,
    DBH.EMPLOYEE_GROSS_AMOUNT,
    DBH.EMPLOYER_GROSS_AMOUNT,
    DBH.PAYROLL_EXCLUDE,
    PTH.VOID_DATE,
    PTH.BATCH_QUEUE_ID,
    B.BATCH_CODE,
    BQ.FY,
    BQ.END_DATE,
    BQ.COMMENTS,
    BQ.BATCH_CRITERIA_USED,
    BP.COLUMN_VALUE,
    PTH.REPLACEMENT,
    P.LAST_NAME,
    P.FIRST_NAME,
    P.MIDDLE_NAME
    from PY_EMPLOYEE_TAX_HISTORY PTH
    INNER JOIN PERSON_EMPLOYEE PE ON
    PE.INST_ID=PTH.INST_ID AND
    PE.EMPLOYEE_ID=PTH.EMPLOYEE_ID
    INNER JOIN PERSON P ON
    PE.INST_ID=P.INST_ID AND
    PE.PERSON_ID=P.PERSON_ID
    LEFT JOIN HR_EMPLOYEE_DEDUCTIONS_AND_BENEFITS_HISTORY DBH ON
    PTH.INST_ID=DBH.INST_ID AND
    PTH.CHECK_DATE=DBH.CHECK_DATE AND
    PTH.CHECK_NO=DBH.CHECK_NO AND
    PTH.EMPLOYEE_ID=DBH.EMPLOYEE_ID
    LEFT JOIN HR_DEDUCTION_AND_BENEFITS DB ON
    DB.INST_ID=DBH.INST_ID AND
    DB.HR_DEDUCTION_AND_BENEFITS_CODE=DBH.HR_DEDUCTION_AND_BENEFITS_CODE
    LEFT JOIN BATCH_QUEUE BQ ON
    PTH.BATCH_QUEUE_ID=BQ.BATCH_QUEUE_ID
    LEFT JOIN BATCH B ON
    B.BATCH_CODE=BQ.BATCH_CODE 
    LEFT JOIN BATCH_PARAMETER BP ON
    BQ.BATCH_QUEUE_ID=BP.BATCH_QUEUE_ID
    AND BP.COLUMN_NAME = 'SUPPRESS_DIRECT_DEPOSIT'
    ------Please change the WHERE condition for date range of the month you need to run this for.
    WHERE PTH.CHECK_DATE >='07/01/2013'
    AND PTH.CHECK_DATE <='07/31/2013'
    and BQ.BATCH_CODE='BAT_PY_PAYCALC'
    and bq.fy=2014
    ORDER BY PTH.INST_ID ,
    PTH.EMPLOYEE_ID,
    DBH.HR_DEDUCTION_AND_BENEFITS_CODE,
    DBH.CHECK_DATE

    Try this code.  The Server name will be the same name when you use SQL Server Management Studio (SSMS).  It is in the login window for SSMS.  I assume you are using SQLSTANDARD (not SQLEXPRESS) which is in the connection string in the code
    below. I also assume you have remote connection allowed in the database.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.SqlClient;
    namespace ConsoleApplication1
    class Program
    const string DATABASE = "Enter Database Name Here";
    const string SERVER = "Enter Server Name Here";
    static void Main(string[] args)
    DateTime startDate = DateTime.Parse("07/01/2013");
    string startDateStr = startDate.ToString("MM/dd/yyyy");
    DateTime endDate = new DateTime(startDate.Year, startDate.Month + 1, 1).AddDays(-1);
    string endDateStr = endDate.ToString("MM/dd/yyyy");
    string connStr = string.Format("Server={0}\\SQLSTANDARD;Database={1};Trusted_Connection= True;", SERVER,DATABASE);
    string SQL = string.Format(
    "select\n" +
    " PTH.INST_ID\n" +
    ",PTH.EMPLOYEE_ID\n" +
    ",DBH.HR_DEDUCTION_AND_BENEFITS_CODE,\n" +
    ",replace(DB.DESCRIPTION,',','')\n" +
    ",DB.WITHHOLDING_LIABILITY_ACCOUNT_MASK\n" +
    ",DBH.HR_DEDUCTION_AND_BENEFITS_ID\n" +
    ",DBH.CHECK_DATE\n" +
    ",DBH.CHECK_NO\n" +
    ",DBH.FIN_INST_ACCT_ID\n" +
    ",replace(replace (DBH.COMMENT,CHAR(10),' '),CHAR(13),' ')\n" +
    ",DBH.HR_DEDUCTION_AND_BENEFIT_CYCLE_CODE\n" +
    ",DBH.LENGTH\n" +
    ",DBH.EMPLOYEE_COMPUTED_AMOUNT\n" +
    ",DBH.EMPLOYEE_BANK_ROUTING_NUMBER\n" +
    ",DBH.EMPLOYEE_ACCOUNT_TYPE\n" +
    ",DBH.EMPLOYEE_ACCOUNT_NUMBER\n" +
    ",DBH.EMPLOYER_COMPUTED_AMOUNT\n" +
    ",DBH.EMPLOYEE_GROSS_AMOUNT\n" +
    ",DBH.EMPLOYER_GROSS_AMOUNT\n" +
    ",DBH.PAYROLL_EXCLUDE\n" +
    ",PTH.VOID_DATE\n" +
    ",PTH.BATCH_QUEUE_ID\n" +
    ",B.BATCH_CODE\n" +
    ",BQ.FY\n" +
    ",BQ.END_DATE\n" +
    ",BQ.COMMENTS\n" +
    ",BQ.BATCH_CRITERIA_USED\n" +
    ",BP.COLUMN_VALUE\n" +
    ",PTH.REPLACEMENT\n" +
    ",P.LAST_NAME\n" +
    ",P.FIRST_NAME\n" +
    ",P.MIDDLE_NAME\n" +
    " from PY_EMPLOYEE_TAX_HISTORY PTH\n" +
    " INNER JOIN PERSON_EMPLOYEE PE ON\n" +
    " PE.INST_ID=PTH.INST_ID AND\n" +
    " PE.EMPLOYEE_ID=PTH.EMPLOYEE_ID\n" +
    " INNER JOIN PERSON P ON\n" +
    " PE.INST_ID=P.INST_ID AND\n" +
    " PE.PERSON_ID=P.PERSON_ID\n" +
    " LEFT JOIN HR_EMPLOYEE_DEDUCTIONS_AND_BENEFITS_HISTORY DBH ON\n" +
    " PTH.INST_ID=DBH.INST_ID AND\n" +
    " PTH.CHECK_DATE=DBH.CHECK_DATE AND\n" +
    " PTH.CHECK_NO=DBH.CHECK_NO AND\n" +
    " PTH.EMPLOYEE_ID=DBH.EMPLOYEE_ID\n" +
    " LEFT JOIN HR_DEDUCTION_AND_BENEFITS DB ON\n" +
    " DB.INST_ID=DBH.INST_ID AND\n" +
    " DB.HR_DEDUCTION_AND_BENEFITS_CODE=DBH.HR_DEDUCTION_AND_BENEFITS_CODE\n" +
    " LEFT JOIN BATCH_QUEUE BQ ON\n" +
    " PTH.BATCH_QUEUE_ID=BQ.BATCH_QUEUE_ID\n" +
    " LEFT JOIN BATCH B ON\n" +
    " B.BATCH_CODE=BQ.BATCH_CODE\n" +
    " LEFT JOIN BATCH_PARAMETER BP ON\n" +
    " BQ.BATCH_QUEUE_ID=BP.BATCH_QUEUE_ID\n" +
    " AND BP.COLUMN_NAME = 'SUPPRESS_DIRECT_DEPOSIT'\n" +
    " WHERE PTH.CHECK_DATE >='{0}'\n" +
    " AND PTH.CHECK_DATE <='{1}'\n" +
    " and BQ.BATCH_CODE='BAT_PY_PAYCALC'\n" +
    " and bq.fy=2014\n" +
    " ORDER BY PTH.INST_ID\n" +
    ",PTH.EMPLOYEE_ID\n" +
    ",DBH.HR_DEDUCTION_AND_BENEFITS_CODE\n" +
    ",DBH.CHECK_DATE", startDateStr, endDateStr);
    SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);
    DataTable dt = new DataTable();
    adapter.Fill(dt);
    jdweng
    Could you elaborate more on what this code does in general?
    Does it generate a table with the data between specified dates? If so, where is the table shown? 
    Where does one enter in the specified start and end dates on the Web Application? Do I have to create start and end date blanks and link them to the code for it to work?
    Sorry for the inconvenience - I'm just really new at this. Thanks!

  • Creating a print button to call a Report Query and pass filters

    If i use the REPORT QUERY option in APEX 4 to create an statement that is the same one used in an interactive report, can I create a link or button to the REPORT QUERY and pass all the session and filter information from the interactive report to the report query?
    This way I can have the interactive report screen where the user can do all sorts of modifications and such and then pass those to the REPORT QUERY so I can call that from a custom link or button.
    You may ask "why does he need another print button?"
    Answer: I am using a view that has some embedded HTML tags to format the output really nicely. The HTML download version created by the interactive reports works beautifully. The customer also wants a PDF version (meh) which does not render the HTML tags and actually echos them as part of the text. I found that I can create another view that uses the CHR function to create all the breaks and such I was doing with HTML and these do render properly in PDF. So, I figured just have 2 reports: 1 Interactive and 1 using a REPORT QUERY. I just want to call the REPORT QUERY version but use the Interactive Search form to set all the parameters.
    Or, am I over thinking this and there is an easier method?
    I made a previous post where I showed how I got the APEX printing to work and i hoped that helped someone out - fixing this issue would put the whole thing to rest.
    Thanks

    Is BI Publisher desktop (MS Word add-in) a possibility? This would allow you to use MS Word to create your output template (RTF) that would result in a properly formatted PDF. Of course, you'd have to right an updated version of the query without HTML embedded. Just thinking outside of the box.

  • Trying to get a Trigger and Alert to work

    So im trying to get a trigger to work with an alert and the Alert seems to be right and the trigger complies which seems right to me, however the instruction that I have in my book does not produce the same output that I get from my Update.
    Here is the deal. I am to log into sql * with a default account as well as login as "SYSTEM"
    the trigger should invoke the Alert and output a message to re-order some more product and the status should = 0 since there is no wait time. However I don't get a "Message" from the Alert and the status = 1 which indicates timeout. So if you can take a look at my code and let me know what I did wrong or how to "Connect" the two that would be great.
    Trigger I created.
    CREATE OR REPLACE TRIGGER order_replace_trg
    AFtER UPDATE OF stock on bb_product
    FOR EACH ROW
    WHEN (OLD.stock = 24 AND NEW.stock = -2)
    DECLARE
    stock NUMBER(5,1);
    idproduct NUMBER(2);
    lv_msg_txt VARCHAR2(25);
    lv_status_num NUMBER(1);
    reorder NUMBER(3);
    BEGIN
    IF stock <> 24 AND reorder = 25 THEN
    lv_msg_txt := 'Product 4 Reorder Time!';
    DBMS_OUTPUT.PUT_LINE(lv_msg_txt);
    ELSE
    lv_status_num := 0;
    DBMS_OUTPUT.PUT_LINE(lv_status_num);
    END IF;
    END;
    The Alert:
    BEGIN
    DBMS_ALERT.REGISTER('reorder');
    END;
    DECLARE
    lv_msg_txt VARCHAR2(25);
    lv_status_num NUMBER(1);
    BEGIN
    DBMS_ALERT.WAITONE('reorder', lv_msg_txt, lv_status_num, 120);
    DBMS_OUTPUT.PUT_LINE('Alert: ' ||lv_msg_txt);
    DBMS_OUTPUT.PUT_LINE('Status: ' ||lv_status_num);
    END;
    Here is the block I need to run to test the trigger and alert.
    UPDATE bb_product
    SET stock = stock -2
    WHERE idproduct = 4;
    COMMIT;
    The message I should get is:
    Alert: Product 4 Reorder Time!
    Status: 0
    PL/SQL procedure successfully completed.
    This is what I get.
    SQL> /
    Alert:
    Status: 1
    PL/SQL procedure successfully completed.
    Thanks for your help!
    Mac

    Right. Register says "I'm interested in getting alerted to some particular event", Waitone says "I'm waiting until some event happens". Signal is the key thing that indicates that a particular event happened.
    As for your trigger, a couple of issues
    - I don't know why you're calling DBMS_OUTPUT. I'm guessing that you probably want to send a message along with your alert that the receiver gets and displays, not that you want to print a message to the window from inside the trigger.
    - You're using the local variables stock and reorder in your IF statement but you never initialize them. I'm guessing that you would want to eliminate those local variables and just use :new.stock and :new.reorder (assuming that REORDER is a column in the table).
    - Your WHEN clause doesn't seem to make sense. It's telling the trigger to fire only if you update stock from 24 to -2, which doesn't make sense. I'm not sure you would even need a WHEN clause here.
    Justin

  • Using different hierarchy in a query and last value error

    Hi guys,
    there is a hierarchy for customers in the 0Customer Infoobject which I should use in my query.
    I have activated the hierarchy in the query and now some results are not appearing but red crosses "x" are shown.
    And the error message: The function Calculate Results as ... could not be applied everywhere.
    I know that I am using the result as "last value" for some columns because I need them there (for example: to determine the last value for the credit limit of the current month). I think these columns where I am using the last value calculation are only affected.
    I mean my query has a lot of characteristics and key figures and I was told that a hiearchy for customers which is available should be used. But now there are these red crosses.
    I don´t see any other solution as not to use this specific hierarchy.
    Has anybody a suggestion what could be an argument to use or not to use a hierarchy?
    Is it sometimes like in my case that a hierarchy is not possible to use?
    Thanks in advance!

    Hi,
    say for example your customer hierarchy is customers grouped under region. You can maintain this region as one of the attribute of customer and you can display this attribute in the report. Indirectly, this will give similar output to that of hierarchy.
    But lot depends on how your hierarchy is formed, before commenting whether it can be moved to master data attributes.
    Thanks.

  • Sap query AND sapnwrfc

    Hi all,
    I have a working "sap query" (sq01).
    This query prints the list of our material catalog (module MM).
    My problem is to write an external program that displays the same output.
    To this purpose I installed "sapnrfc".
    All works correctly: I can connect to SAP, read a table (for example MARAV) and output the content.
    In SAPGui (sq01), I selected "InfoSet Query" and then "Display field information".
    I see (for example) that the "Material Number" is stored in the table MARAV (field MATNR).
    The problem is that in my "sap query" there are a couple of fields that I do not know where they come from.
    Selecting "Display field information" for these fileds I only see:
    TXT_ITA (Additional field)
    TXT_TET (Additional filed)
    Where is this information stored ?
    Perhaps there is a view ... or a better method.
    Thanks for any help.
    Miche

    Dear Sathya,
    SAP does not allow you to rename SAP Query & Info set at a same time.
    Note:
    The system has to lock the following objects before you are able to use the Rename SAP Info set function:
    User group catalog
    Info Set catalog
    Query catalogs for user groups to which the Info Set that you are renaming is assigned,
    Queries using this Info Set
    Once all these locks have been set, the system can carry out the function.
    Renaming an Info Set can, however, be very time-consuming. These locks may also prevent other users from working in the system for as long as it takes to rename the Info Set.
    Thanks & Regards
    Dinu

Maybe you are looking for