Delete results of subquery function of selected inital collection

;with myresult as (SELECT *
FROM [Barcode].[dbo].[ContainerHistory]
WHERE dateEntered >= DATEADD(day, DATEDIFF(day, 0, getDate()) -1, 0)
AND dateEntered < DATEADD(day, DATEDIFF(day, 0, getDate()), 0)
AND stateID = 1
AND (SELECT dbo.fn_checkExpiration(containerID) AS containerExpire FROM [Barcode].[dbo][ContainerHistory] WHERE containerExpire = 1)
WHERE (@@ROWCOUNT > 1)
DELETE FROM myresult
create table [Barcode].[dbo].ContainerHist
changeTypeID varchar(64),
containerID varchar(20),
stateID int,
dateEntered datetime,
note varchar(20)
INSERT INTO [Barcode].[dbo].CotainerHist (changeTypeID, containerID, stateID, dateEntered, note)
VALUES ('UPDATE','6210110310002','1','2014-11-09 15:42:58.437','note1')
INSERT INTO [Barcode].[dbo].CotainerHist (changeTypeID, containerID, stateID, dateEntered, note)
VALUES ('NEWDATE','6210110310003','2','2014-11-09 16:42:58.437','null')
INSERT INTO [Barcode].[dbo].CotainerHist (changeTypeID, containerID, stateID, dateEntered, note)
VALUES ('UPDATE','6210110310002','1','2014-11-09 17:42:58.437','note1')
;with myresult as (SELECT *
FROM [Barcode].[dbo].ContainerHist
WHERE dateEntered >= DATEADD(day, DATEDIFF(day, 0, getDate()) -1, 0)
AND dateEntered < DATEADD(day, DATEDIFF(day, 0, getDate()), 0)
AND stateID = 1
AND (SELECT dbo.fn_checkExpiration(containerID) AS containerExpire FROM [Barcode].[dbo][ContainerHist] WHERE containerExpire = 1)
IF (@@ROWCOUNT > 1)
DELETE FROM myresult
drop table [Barcode].[dbo].ContainerHist
The first query is working correctly, but I need to make a subquery based on a Boolean result of true or false that an container item has expired which is calculated as today >  previous date + some age constant in days and that works. 
How do I need to write the sub query from the first query results?
This will need to run as scheduled job in the sql server agent after midnight.

Hi tonofit,
Based on your description, as far as I can understand, the code you posted is supposed to run as a scheduled job to clean up the expired records, right?
Obviously the code doesn’t work for some syntax errors. Please notice the
bold numbers and see the comments below.
with myresult as (SELECT *
FROM [Barcode].[dbo].[ContainerHistory]
WHERE dateEntered >= DATEADD(day, DATEDIFF(day, 0, getDate()) -1, 0)
AND dateEntered < DATEADD(day, DATEDIFF(day, 0, getDate()), 0)
AND stateID = 1
AND(1) (SELECT dbo.fn_checkExpiration(containerID) AS containerExpire FROM [Barcode].[dbo][ContainerHistory] WHERE containerExpire(2) = 1)
(3)
      (1) A search condition expression should be after a
AND rather than a single subquery.
      (2) A Column alias before WHERE
can’t appear after the WHERE. Chronologically, SELECT
           happens After
WHERE, which always is the last step in the execution chain.
      (3) A right parenthesis missed.
Since you didn’t post code of the User-Defined Function(UDF) fn_checkExpiration, according to the subquery after the last
AND, I guess that the UDF returns 1 if the parameter containerID is calculated as expired. Please see the below sql which could achieve your requirement.     
WITH MyResult AS
SELECT dbo.fn_checkExpiration(containerID) AS containerID
FROM [Barcode].[dbo].ContainerHistory
WHERE dateEntered >= DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP) -1, 0)
AND dateEntered < DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
AND stateID = 1
DELETE MyResult WHERE containerID=1
In addition, the date search conditions only select the data of “yesterday”. If your job doesn’t run “today” for any reason, when it runs “tomorrow”, the data of the “yesterday” gets filtered out and corrupted. Please take this into account.
Best Regards,
Eric Zhang

Similar Messages

  • TS3274 In my iPad's Photo folder, after I select edit, and apply check marks to specific photos, the red 'Delete' button does not function.  How do I correct this issues?

    To anyone familiar with iPad 2s,
    After I select the Sunflower Photo icon and touch 'Edit', apply check marks to specific photos I want deleted, the red 'Delete button doesn't function.  How do I correct this?
    Thanks

    The links below have instructions for deleting photos.
    iOS and iPod: Syncing photos using iTunes
    http://support.apple.com/kb/HT4236
    iPad Tip: How to Delete Photos from Your iPad in the Photos App
    http://ipadacademy.com/2011/08/ipad-tip-how-to-delete-photos-from-your-ipad-in-t he-photos-app
    Another Way to Quickly Delete Photos from Your iPad (Mac Only)
    http://ipadacademy.com/2011/09/another-way-to-quickly-delete-photos-from-your-ip ad-mac-only
    How to Delete Photos from iPad
    http://www.wondershare.com/apple-idevice/how-to-delete-photos-from-ipad.html
    How to: Batch Delete Photos on the iPad
    http://www.lifeisaprayer.com/blog/2010/how-batch-delete-photos-ipad
    (With iOS 5.1, use 2 fingers)
    How to Delete Photos from iCloud’s Photo Stream
    http://www.cultofmac.com/124235/how-to-delete-photos-from-iclouds-photo-stream/
     Cheers, Tom

  • Oracle db wrong result on subquery error

    Hi,
    I work with Oracle databases up to 10g and I found an error and couldn’t find any documentation about it yet. Perhaps you can help me.
    The error is quite easy to replicate. If you run the following query adapting the parameters you should get a result, the problem is that you should only get an error!
    select * from user_tab_columns
    where table_name in
    select table_name from <TABLE_B>
    Parameter: TABLE_B
    Description: This should be an existing table of the schema which doesn’t have any table_name field.
    As I said, the sub-query is wrong, so if you try to run it separately it fails. The problem is when you run both together because, if the link field has the same name, it returns all values of the table in the outer query.
    Do you know if this is solved in 11g or in a specific patch of 10g?
    Thanks in advance for your interest.
    Best regards,
    Leo ([email protected])

    user6396183 wrote:
    I don't think a query whose inner query evaluates to ORA-00904 'Invalid identifier' should return anything, it's not logic. To me this is a bug.
    If you execute the following query it will retrieve all records from the outer table when it should only return an exception as the inner query can not be evaluated at all.
    select * from user_tab_columns
    where table_name in (select table_name from user_role_privs);You still did not get it. Yes inner query by itself results in ORA-00904 'Invalid identifier' only if you execute it independently:
    select table_name from user_role_privsOracle parser tries to figure out what table_name is. It is not a literal, therefore it concludes it is an identifier. Now the only table in FROM list is user_role_privs and it has no such column. Then parser checks if such function exists and it does not, etc... At the end ORA-00904 'Invalid identifier' is raised. However, look what happens if you issue it as a sub_query:
    select * from user_tab_columns
    where table_name in (select table_name from user_role_privs);Again, Oracle parser tries to figure out what table_name is. It is not a literal, therefore it concludes it is an identifier. Now the only table in FROM list is user_role_privs and it has no such column. Now, parser realizes it is a subquery and table_name can be a correlated name. So it checks main query FROM clause list and guess what - table user_tab_columns has a column table_name. So what subquery means is select a row from table user_tab_columns, which will give as some column table_name value and then use that value in subquery, get results and compare it with same table_name value. Now, I hope, you can see that no error should be raised. And, if user_role_privs is not empty, query will return every row in user_tab_columns. If user_role_privs is empty, query will not return any rows. But again, error is neither raised nor should be raised.
    SY.

  • Calling User definedTable valued function in Select

    Hello,
    I Created a UserDefined Table Valued Function in HANA.
    I need to call it in Select Statement Statement.
    For Example
    Select Func(col1) as test,col2 from tablename;
    While using UserDefined Table Valued Function in above select statement
    I am getting following error
    cannot use procedure or table function in select projection
    Please help me

    Dont think you can do that Krishna,
    A Tabel UDF is expected to return a row of results and not just a scalar value. A SELECT <value> on the other hand can only expect a single value. Maybe you could try SELECT  (SELECT TOP 1 <column name> from TABLEUDF() ) from....
    Regards,
    Nehal.

  • I have a 60G classic with a non-functioning center select button. Can I set a specific playlist and change settings by hooking up to my PC and then maintain those settings and that playlist once I go remote?

    I have a 60G classic with a non-functioning center select button. Can I set a specific playlist and change settings by hooking up to my PC and then maintain those settings and that playlist once I go remote?

    I'm having a little trouble understanding the part about your password having to be reset. Why is that happening??
    Let's start with Firefox's settings:
    (1) You can configure the password manager feature on this tab:
    orange Firefox button (or Tools menu) > Options > Security
    There is a checkbox to enable/disable the feature.
    There also is a "Saved Passwords" button to review and remove any passwords you do not want Firefox to keep.
    That tab also has a feature to set a Master Password so that no one can use your saved passwords without knowing the Master Password. You may need to exit Firefox in order for Firefox to ask for that again.
    Related articles:
    * [[Password manager - Remember, delete and change saved passwords in Firefox]]
    * [[Use a Master Password to protect stored logins and passwords]]
    (2) Site-specific permissions
    If you want to use the password manager for other sites but NOT a particular site, you can configure that in the Permissions Manager.
    In a new tab, type or paste '''about:permissions''' in the address bar and press Enter.
    After the page loads, use the search box in the upper left corner to narrow down the list to the site you want to configure. Highlight the site on the left side, and on the right side, choose Block under Store Passwords.
    (3) Form autocomplete suggestions
    Separate from passwords, Firefox remembers entries you've made into forms (in most cases) and lists the matching ones below the form field in a drop-down.
    To clear a suggestion, press the down arrow key to highlight it and press the Delete key.
    To turn off this feature, see this article: [[Control whether Firefox automatically fills in forms with your information]].
    To review and selectively edit or delete form history entries, you need an add-on. For example, you could try this one: https://addons.mozilla.org/firefox/addon/form-history-control/

  • Using the result of a function, inside a subselect

    Hi!
    I´m wondering if it´s possible to use the result of a function inside a subselect. Let me give you an example of what I´m trying to do here:
    select * from t_node where node_pk in (get_node_parents_pk(22345));
    The function get_node_parents_pk stands in for the following SELECT-statment:
    select node_pk from t_node_child where parent_node_pk = 12345
    The statement above would return something like this: 12435,23423,23453,23452
    These values represent the node_pk value for the parent nodes.
    I want the get_node_parents_pk function to return a result set similar to this so that I might call it inside the IN ( ) statement.
    Any clue? =)

    I created a collection type in the database:
    CREATE OR REPLACE TYPE nodes_pk_arr IS TABLE OF INTEGER;
    The function get_node_parents_pk () is made to return the collection type above. However, this does not work. I get the following error message:
    SELECT *
    FROM t_node
    WHERE node_pk IN
    (SELECT * FROM TABLE (get_node_parents_pk (22345)));
    ORA-22905: cannot access rows from a non-nested table item
    However, if I insert a nodes_pk_arr collection directly into the SQL-statement, like I do below, it works:
    SELECT *
    FROM t_node
    WHERE node_pk IN
    (SELECT * FROM TABLE (nodes_pk_arr(24564,23545,34523));
    So, when returning the collection from the function I´m told that the collection is not a nested table, when in fact it is. What gives?
    Also, is there no way to return a result set directly from the get_node_parents_pk() function, making it possible to write the statement like that shown below?
    SELECT *
    FROM t_node
    WHERE node_pk IN (get_node_parents_pk (22345));
    Your reply is much appreciated!
    Kind regards
    Robert

  • Passing results to another function in MDX

    I'm pretty sure I know the answer to this, but it would be cool if it worked, so I figured I would put it out there and see if anyone successfully did this.<BR><BR>Is it possible to pass the result of a function NonEmptyCount() as an index for another function Item()?<BR><BR>Example<BR>CrossJoin({[Time].Levels(0).members},<BR>{[Measures].[Headcount]}).Item(NonEmptyCount(<BR>[Time].Levels(0).members, [Measures].[Headcount]<BR>))

    I found the solution to my problem.
    [1] Create a "After Submit" under Computations.
    [2] Select 'Item Value' under Type in Item Name
    [3] Select "After Submit" under Computation Point
    [3] Enterer Item Name, which value needs to be passed in 'Source'
    thanks

  • Call function with select arguments

    Hi Gurus,
    I have problem to call function inside select statements as follow:
    select a.ID_ELE2, a.ID_ELE3, a.DT_FIS_YR, c.NU_FIS_PER, c.dt,
    (case
    when c.ld is null then
    GET_LD_CHECK (a.DT_FIS_YR,c.NU_FIS_PER, a.ID_ELE3, a.ID_ELE2) -- 1
    -- GET_LD_CHECK ('2009',7, '8010', '7493') --- 2
    else
    c.ld
    end ) description
    from ACCOUNT a, TRANSACTION c
    where a.DT_FIS_YR ='2009'
    and a.ID_ELE3 <> '0000'
    and c.TY_SRC not in ('CL', 'CN')
    and a.DT_FIS_YR = c.nu_fis_yr
    and a.AK = c.AK_FGCHAR
    and trim(a.ID_ELE3) ='8010'
    and c.NU_FIS_PER <> 14
    order by 1,4,5,6
    the 1 doesn't output result but the 2 it does! How can pass the select result to the function?
    Thanks in advance for your help.
    Ben

    The statement / function call seems to be ok. So there are not much chances left for your call to return different (=non) values.
    1) It could be that you have different values in the column then during your test call.
    2) Maybe your function raises an error and that error is supressed in some ugly WHEN OTHERS EXCEPTION => Solution: Get rid of the error handler.
    3) datatype conversion. For example if a.dt_fis_yr is a number value, then you should test with number values and not with strings. GET_LD_CHECK (2009,7, '8010', '7493'). Same logic goes for the other paramters, make sure the datatype is correct and matches the function parameter.

  • Delete results from analyzer

    How can I delete results from the quiz results analyzer? I have an exam that wont download completely on one computer so I'm thinking if I can clean it out that'd be fantastic and might help.
    On windows 7.

    Hi,
    In order to delete results from the Quiz Results Analyzer (Assusming , you are working on Captivate 5/5.5) and you want to delete the complete course, please follow the steps:-
    1.) Select the course that you want to delete that you want to delete under Quiz Results analyzer
    2.) At the Top right corner, you may find the Tab " Delete from Acrobat.com "if you are signed into Acrobat.com.
    3.)Click on that and it may delete the course.
    Note:- In Captivate 5.0/5.5 Quiz Results Analyzer, only courses can be deleted but Organization and Department name can not be deleted
    I hope that answers your query.

  • Result for one Function und one titel in one colum

    Hello,
    it is possible to put one result form a function and another colum in only one colum?
    Thank you, very much :-)
    Chris from Germany

    Sure:
    SQL> create or replace
      2  function f1(n number)
      3  return number
      4  is
      5  begin
      6  return n;
      7  end;
      8  /
    Function created.
    SQL> select ename,f1(sal),comm,f1(sal) + nvl(comm,0) from emp
      2  /
    ENAME         F1(SAL)       COMM F1(SAL)+NVL(COMM,0)
    SMITH             800                            800
    ALLEN            1600        300                1900
    WARD             1250        500                1750
    JONES            2975                           2975
    MARTIN           1250       1400                2650
    BLAKE            2850                           2850
    CLARK            2450                           2450
    SCOTT            3000                           3000
    KING             5000                           5000
    TURNER           1500          0                1500
    ADAMS            1100                           1100
    ENAME         F1(SAL)       COMM F1(SAL)+NVL(COMM,0)
    JAMES             950                            950
    FORD             3000                           3000
    MILLER           1300                           1300
    14 rows selected.
    SQL> SY.

  • When I access my google e-mail account on the I-pad my inbox has at least 6 e-mails with no sender and no subject (absent via I-phone, Mac or PC) I cannot delete them as they cannot be selected- how do I stop them and clear the ones there now?

    When I access my google e-mail account on the I-pad my inbox has at least 6 e-mails with no sender and no subject (absent via I-phone, Mac or PC) I cannot delete them as they cannot be selected- how do I stop them and clear the ones there now?

    Try turning the account off and on : Settings > Mail, Contacts, Calendars , then tap the account on the right, slide Mail to 'off', exit settings and go back into the Mail app, and then go back to Settings and slide Mail back to 'on'
    If that doesn't work then try closing the Mail app completely : from the home screen (i.e. not with the Mail app 'open' on-screen) double-click the home button to bring up the taskbar, then press and hold any of the apps on the taskbar for a couple of seconds or so until they start shaking, then press the '-' in the top left of the Mail app to close it, and touch any part of the screen above the taskbar so as to stop the shaking and close the taskbar.
    Also do a reset : press and hold both the sleep and home buttons for about 10 to 15 seconds (ignore the red slider), after which the Apple logo should appear - you won't lose any content, it's the iPad equivalent of a reboot.

  • HOW CAN I DELETE AN EVENT WITHOUT  HAVING TO SELECTING IT FROM THE LIBRARY?

    I have a big problem.
    I want to delete an entire event from my library because everytime I select it imovie freezes and then close itself up. So I have to re-open imovie again. And when I want to select that particular event again the same problem occures. So I can not select that particular event. Therefore I can take NO action on this event.
    HOW CAN I DELETE AN EVENT WITHOUT HAVING TO SELECTING IT FROM THE LIBRARY?
    (Everytime I select it imovie closes itself up)
    All other events work fine. I believe The footage had a problem from capturing. but now it's in my computer and i can't open it.
    Please help me, I don't need this event, I can't open it therefore I can't use it and it takes place on my hardrive for nothing.
    Thank you

    One can delete it from one's computer. In the finder go to homeuser, movies, imovie events, delete the footage.
    Then reopen iMovie and see if that helps.
    Hugh

  • Delete Results for workbook layout in BI.7

    Hi Experts,
    How to delete results of Query from the Work to Save it as a Blank Workbook Template in BI .7. As we have option in 3.x like Tools->all queries in the Workbook-> Delete Results.
    Thanks
    DB

    Hi,
    refer to this link:
    BEx Analyzer [Analyse mode|http://help.sap.com/saphelp_nw70/helpdata/en/e3/e60138fede083de10000009b38f8cf/frameset.htm]
    U have to insert an analysis grid where u can choose a DataProvider (Query)
    Information to other design elemets for BEx Workbooks u find at [SAP Help|http://help.sap.com/saphelp_nw70/helpdata/en/e1/8e51341a06084de10000009b38f83b/frameset.htm]
    Regards
    Edited by: Tobias on May 19, 2008 4:49 PM

  • Using function in select statement

    Hi,
    CREATE FUNCTION [dbo].[udf_testFunction] 
    @value int
    RETURNS int
    AS
    BEGIN
    -- Declare the return variable here
    declare @returnValue int
    set @returnValue = @value*2;
    return @returnValue;
    END
    GO
    create table #Temp
        EmpID int, 
        EmpName Varchar(50)
    insert into #Temp(EmpID,EmpName) values(1,'Name1');
    insert into #Temp(EmpID,EmpName) values(2,'Name2');
    insert into #Temp(EmpID,EmpName) values(3,'Name3');
    insert into #Temp(EmpID,EmpName) values(4,'Name4');
    insert into #Temp(EmpID,EmpName) values(5,'Name5');
    select EmpID,EmpName, [dbo].[udf_testFunction](EmpID), [dbo].[udf_testFunction](EmpID)*EmpID,[dbo].[udf_testFunction](EmpID)+2 from #Temp
    In the above select statement i used [dbo].[udf_testFunction]() function 3 times. But i want to use only once and reuse it.
    Something like 
    select EmpID,EmpName, testfunctionvalue,testfunctionvalue*EmpID,testfunctionvalue+2 from #Temp
    Please advise me.... Thanks in Advance...

    You can use this code: 
    WITH cte
    AS ( SELECT EmpID ,
    EmpName ,
    [dbo].[udf_testFunction](EmpID) AS testfunctionvalue
    FROM #Temp
    SELECT EmpID ,
    EmpName ,
    testfunctionvalue ,
    testfunctionvalue * EmpID ,
    testfunctionvalue + 2
    FROM cte
    But using scalar functions in select clause can hurt the performance. Please see this link: 
    SQL Server Scalar User Defined Function Performance
    T-SQL Articles
    T-SQL e-book by TechNet Wiki Community
    T-SQL blog

  • PL/SQL Function in Select statement

    Hi
    I am calling a function in select statement. The query works in Toad and PL/SQL developer except SQL plus and disconnecting Oracle connection.
    The error is “ERROR at line 1: ORA-03113: end-of-file on communication channel”.
    When I called the same query from BC4J View Object the error message is “java.sql.SQLException: No more data to read from socket”.
    Can any one advise me please?
    Thanks
    Srini

    Srini
    I've seen similar cases in the past with 9.2.0.x (x <= 5). What Oracle version are you using? It's worth checking the bug database (I can't just now - I don't have a valid support id in my current contract). And as Warren says, post your SQL query.
    HTH
    Regards nigel

Maybe you are looking for