Union select over temp table

Hi,
I have a question about the best solution in selecting data from two tables and one of it is a temp table.
If ID is found on both tables, only the temp_table row should be selected. My solution looks like:
ORIG_TABLE
PK_ID
Data1
Data2
status_cd
TEMP_TABLE
PK_ID
Data1
Data2
status_cd
select data1, data2, status_cd from ORIG_TABLE
  where pk_id not in (select pk_id from temp_table)
union
select data1, data2, status_cd from TEMP_TABLEI wonder if there is an easier way in selecting data like that.
Thanks ahead,
Tobias

Tobias Arnhold wrote:
I wonder if there is an easier way in selecting data like that.I think your current apporach is probably the best solution (You may want to replace UNION with UNION ALL though depending upon whether you expect (and need or not) duplicate records). You may want to keep an eye on the execution plan of the query using NOT IN if the temp table is a GTT (global temporary table) since maintaining statistics on a GTT can be tricky.
Edited by: user503699 on Nov 4, 2010 3:20 PM - Added comment about UNION

Similar Messages

  • Multiple selection over mualtiple tables in one panel.

    GUI is having 3 JTables placed in one JPanel.
    User is able to select one row fron each table using mouse over a row and drag it. How this can be stop ????
    Step :-
    one JPanel (Ex. jp).
    Three JTable (ex. jt1, jt2 and jt3)placed in above JPanel.
    No row is selected from any table.
    Select one row from jt1.
    Go to jt2 press mouse over one row and drag it(don't release mouse.)
    after coming out of row release.
    Same action can do with jt3 also.
    But this is not required one.
    Provide the solution that user must not be able to select row form more than one row at a time.

    It appears there is no solution out there but I did manage to find something else for myself:
    I now use only two desktops, each one is fixed to one monitor and through this, tint2 splits it in half which actually is pretty nice, since I can now switch around windows on monitors via taskbar.
    Should the need for more desktops arise, I will probably use some kind of composite cube or something which will provide the functionality, too.

  • Select into Temp Table Identity Column

    I'm trying to select data into a temp table but how would I select the identity column into my temp table. This is what I have so far(RefId is the identity Column (1,1)
    BEGIN TRAN
    SELECT [RefId]
    ,[Name]
    ,[CreationDate]
    ,[CreatedBy]
    ,[ModificationDate]
    ,[ModifiedBy]
    ,[RegistrationNumber]
    ,[EmployerType]
    ,[EmployerState]
    ,[ProviderLegalDescription]
    ,[WeeklySalaryDateType]
    ,[WeeklySalaryDateDay]
    ,[FortnightlySalaryDateType]
    ,[FortnightlySalaryDateDay]
    ,[MonthlySalaryDateType]
    ,[MonthlySalaryDateDay]
    ,[TrustLevel]
    ,[ForceDeductionOverrides]
    ,[PayrollPaypointlDeductionsEnabled]
    ,[PaypointRefId]
    ,[PayrollBackupEnabled]
    ,[PayrollBackupFailedPaymentsBefore]
    ,[PayrollBackupType]
    ,[PayrollBackupUploadType]
    ,[PayrollBackupEnableAutomation]
    ,[PayrollBackupAutomationType]
    ,[PayrollBackupFtpServer]
    ,[PayrollBackupFtpPort]
    ,[PayrollBackupFtpPassword]
    ,[PayrollBackupEmail]
    ,[PayrollBackupFtpUsername]
    ,[EnforceSingleProduct]
    ,[AffordabilityOverride]
    ,[AffordabilityReoccuringIncomePercent]
    ,[AffordabilityAdHocIncomePercent]
    ,[AffordabilityVariableIncomePercent]
    ,[AffordabilityNumerator]
    ,[AffordabilityExposure]
    ,[ExternalIdentificationNumber]
    ,[DeductionType]
    ,[IsValidated]
    ,[ValidatedBy]
    ,[ValidatedDate] INTO #TempEmployers FROM Employers WHERE RefId=2
    SELECT
    Name, COUNT(*) AS Repeats INTO #Temp
    FROM
    Employers
    GROUP BY
    Name
    HAVING
    COUNT(*) > 1
    Declare @Nam nvarchar(250)
    While (Select Count(*) From #Temp) > 0
    Begin
    Select Top 1 @Nam = Name From #Temp
    --Do some processing here
    Delete #Temp Where @Nam = Name
    INSERT INTO #TempEmployers
    SELECT [RefId]
    ,[Name]
    ,[CreationDate]
    ,[CreatedBy]
    ,[ModificationDate]
    ,[ModifiedBy]
    ,[RegistrationNumber]
    ,[EmployerType]
    ,[EmployerState]
    ,[ProviderLegalDescription]
    ,[WeeklySalaryDateType]
    ,[WeeklySalaryDateDay]
    ,[FortnightlySalaryDateType]
    ,[FortnightlySalaryDateDay]
    ,[MonthlySalaryDateType]
    ,[MonthlySalaryDateDay]
    ,[TrustLevel]
    ,[ForceDeductionOverrides]
    ,[PayrollPaypointlDeductionsEnabled]
    ,[PaypointRefId]
    ,[PayrollBackupEnabled]
    ,[PayrollBackupFailedPaymentsBefore]
    ,[PayrollBackupType]
    ,[PayrollBackupUploadType]
    ,[PayrollBackupEnableAutomation]
    ,[PayrollBackupAutomationType]
    ,[PayrollBackupFtpServer]
    ,[PayrollBackupFtpPort]
    ,[PayrollBackupFtpPassword]
    ,[PayrollBackupEmail]
    ,[PayrollBackupFtpUsername]
    ,[EnforceSingleProduct]
    ,[AffordabilityOverride]
    ,[AffordabilityReoccuringIncomePercent]
    ,[AffordabilityAdHocIncomePercent]
    ,[AffordabilityVariableIncomePercent]
    ,[AffordabilityNumerator]
    ,[AffordabilityExposure]
    ,[ExternalIdentificationNumber]
    ,[DeductionType]
    ,[IsValidated]
    ,[ValidatedBy]
    ,[ValidatedDate] FROM Employers
    WHERE Name= @Nam
    End
    SELECT * FROM #TempEmployers
    ROLLBACK

    Hi,
    Its the RefId column, I just need the actual values. Im getting the following error:
    Column name or number of supplied values does not match table definition. And it points to The RefId
    Column
    If your question is regarding passing explicit values for identity column you need to set IDENTITY_INSERT to ON and pass a columnlist for the table
    Which column in this is IDENTITY?
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Problems when selecting from temp table

    I have a php script wich creates a temporary table with this command:
    "create global temporary table temp_ouput(...)"
    All is ok.
    Then I insert a lot of data and it doesn't complain.
    Then I attempt to select all records but I end up with an empty set. I mean, it doesn't return any records.
    What's wrong here?

    Are you using the ON COMMIT PRESERVE ROWS option? If not, your data will be deleted as soon as you commit after your insert.
    If you do use this option, you need to clear the table yourself if you are re-using the temp table within your session.

  • CTE into temp table

    I have query with many CTE:
    ;WITH CTE AS(...), CTE1 AS(....), CTE2 AS (...), CTE3 AS(...)
    CTE4 AS(...), CTE5 AS(...), CTE6 AS(...), CTE7 AS(...), CTE8 AS(...), CTE9 AS(...), CTE10 AS(...), CTE11 AS(...)
    SELECT * FROM CTE9 INNER JOIN CTE11 ON....
    The last select works 3 minutes, but until CTE11 everything works in 1 second.
    Is it possible to store CTE9 and CTE11 into temp table? (the same select form temp tables would execute immediately)
    CTE9 and CTE11 has inside access to previous CTE's, so I can't break the query before CTE11 unless I create every CTE as temp table.

    "I think it is too fragile."
    If I store in physical table instead of temp table than if server go down, at least I will
    have my data stored.
    And it is not critical if this records are not available in main table for some time.
    It could be solution, but requires some maintenance work in case server goes down or any other
    uncatchable error .
    But i guess I will just disable escalation.
    My problem is quite simple. I have table "dbo.Stock" where is stock of products in warehouse. Lets say 1 million of products with some quantity. Each quantity of product has some ownership.
    For example: i have quantity 1000 of product A. 500 quantity belongs to company1, 300 to company2 and 200 to company3.
    Then at some time, I have to rearrange the ownership of lets say 200000 products(20%). (could be any number, more or less).
    Until new ownership is not known, this stock should not be available for any operation - so, it is no problem, if this stock doesn't exists in table "dbo.Stock" at calculation time. But for other stock(800.000 products) all operations must be available.
    So, i move(delete) this 200.000 products out of stock table and calculate ownership. This calculation
    runs for 10 minutes. Then I move this stock back to the table(PK of most of the records is different now, so couldn't be update anyway).
    Can you image that this table is locked for 10 minutes and it is very frequent one? Everything would stop for 10 minutes and i will get fired :)
    What function? Do you have some description? I'm curious, maybe get some idea :)
    Thanks,
    Simon

  • A better way than a global temp table to reuse a distinct select?

    I get the impression from other threads that global temp tables are frowned upon so I'm wondering if there is a better way to simplify what I need to do. I have some values scattered about a table with a relatively large number of records. I need to distinct them out and delete from 21 other tables where those values also occur. The values have a really low cardinality to the number of rows. Out of 500K+ rows there might be a dozen distinct values.
    I thought that rather than 21 cases of:
    DELETE FROM x1..21 WHERE value IN (SELECT DISTINCT value FROM Y)
    It would be better for performance to populate a global temp table with the distinct first:
    INSERT INTO gtt SELECT DISTINCT value FROM Y
    DELETE FROM x1..21 WHERE value IN (SELECT value FROM GTT)
    People asking questions about GTT's seem to get blasted so is this another case where there's a better way to do this? Should I just have the system bite the bullet on the DISTINCT 21 times? The big table truncates and reloads and needs to do so quickly so I was hoping not to have to index it and meddle with disable/rebuild index but if that's better than a temp table, I'll have to make do.
    As far as I understand WITH ... USING can't be used to delete from multiple tables or can it?

    Almost, but not quite, as efficient as using a temporary table would be to use a PL/SQL collection and FORALL statements and/or referencing the collection in your subsequent statements). Something like
    DECLARE
      TYPE value_nt IS TABLE OF y.value%type;
      l_values value_nt;
    BEGIN
      SELECT distinct value
        BULK COLLECT INTO l_values
        FROM y;
      FORALL i IN 1 .. l_values.count
        DELETE FROM x1
         WHERE value = l_values(i);
      FORALL i IN 1 .. l_values.count
        DELETE FROM x2
         WHERE value = l_values(i);
    END;or
    CREATE TYPE value_nt
      IS TABLE OF varchar2(100); -- Guessing at the type of y.value
    DECLARE
      l_values value_nt;
    BEGIN
      SELECT distinct value
        BULK COLLECT INTO l_values
        FROM y;
      DELETE FROM x1
       WHERE value = (SELECT /*+ cardinality(v 10) */ column_value from table( l_values ) v );
      DELETE FROM x2
       WHERE value = (SELECT /*+ cardinality(v 10) */ column_value from table( l_values ) v );
    END;Justin

  • GRANT SELECT to TEMP(by procedure)..... ALL tables and views of OWNER....

    hi ,
    I want to privelege only Grant SELECT ALL tables,views....
    I have written A procedure.....given below....
    CREATE OR REPLACE PROCEDURE GRANT_SELECT_ALL_PROC
    IS
    l_obj VARCHAR2(60);
    l_obj_type VARCHAR2(60);
    CURSOR Cur_Obj IS
    SELECT OBJECT_NAME,OBJECT_TYPE
    FROM USER_OBJECTS
    WHERE USER ='OWNER';
    BEGIN
    For i in Cur_Obj Loop
    l_obj := i.OBJECT_NAME;
    l_obj_type := i.OBJECT_TYPE;
    IF l_obj_type IN ('TABLE','VIEW')
    THEN
    EXECUTE IMMEDIATE 'GRANT SELECT ON' || l_obj ||'TO TEMP’;
    ELSIF l_obj_type IN('FUNCTION','PROCEDURE','PACKAGE') THEN
    EXECUTE IMMEDIATE 'GRANT EXECUTE ON'|| l_obj ||'TO TEMP’;
    END IF;
    END LOOP;
    END GRANT_SELECT_ALL_PROC;
    procedure is working fine.....
    OWNER there are some table and views......
    But After creation of User name TEMp....
    When I m giving GRANT SELECT to TEMP(by procedure)..... ALL tables and views of OWNER....
    when I coonecte to TEMP...
    Not getting table,view List...
    not even data of table or Views.....
    can anybdy help me.......advance thanx ...
    sanjay

    hi ,
    I want to privelege only Grant SELECT ALL
    tables,views....
    have written A procedure.....given below....
    CREATE OR REPLACE PROCEDURE GRANT_SELECT_ALL_PROC
    IS
    l_obj VARCHAR2(60);
    l_obj_type VARCHAR2(60);
    CURSOR Cur_Obj IS
    SELECT OBJECT_NAME,OBJECT_TYPE
    FROM USER_OBJECTS
    WHERE USER ='OWNER';
    BEGIN
    For i in Cur_Obj Loop
    l_obj := i.OBJECT_NAME;
    l_obj_type := i.OBJECT_TYPE;
    IF l_obj_type IN ('TABLE','VIEW')
    THEN
    EXECUTE IMMEDIATE 'GRANT SELECT ON' || l_obj ||'TO
    TEMP’;
    ELSIF l_obj_type IN('FUNCTION','PROCEDURE','PACKAGE')
    THEN
    EXECUTE IMMEDIATE 'GRANT EXECUTE ON'|| l_obj ||'TO
    TEMP’;
    END IF;
    END LOOP;
    END GRANT_SELECT_ALL_PROC;
    procedure is working fine.....
    OWNER there are some table and views......
    But After creation of User name TEMp....
    When I m giving GRANT SELECT to TEMP(by
    procedure)..... ALL tables and views of OWNER....
    when I coonecte to TEMP...
    Not getting table,view List...
    not even data of table or Views.....
    can anybdy help me.......advance thanx ...
    sanjayQuery SELECT * FROM USER_TAB_PRIVS_MADE from the user from which you are executing the procedure
    and Query SELECT * FROM USER_TAB_PRIVS_RECD from the TEMP user.

  • Global Temp Table or Permanent Temp Tables

    I have been doing research for a few weeks and trying to comfirm theories with bench tests concerning which is more performant... GTTs or permanent temp tables. I was curious as to what others felt on this topic.
    I used FOR loops to test out the performance on inserting and at times with high number of rows the permanent temp table seemed to be much faster than the GTTs; contrary to many white papers and case studies that have read that GTTs are much faster.
    All I did was FOR loops which iterated INSERT/VALUES up to 10 million records. And for 10 mil records, the permanent temp table was over 500k milliseconds faster...
    Anyone have an useful tips or info that can help me determine which will be best in certain cases? The tables will be used for staging for ETL Batch processing into a Data Warehouse. Rows within my fact and detail tables can reach to the millions before being moved to archives. Thanks so much in advance.
    -Tim

    > Do you have any specific experiences you would like to share?
    I use both - GTTs and plain normal tables. The problem dictates the tools. :-)
    I do have an exception though that does not use GTTs and still support "restartability".
    I need to to continuously roll up (aggregate) data. Raw data collected for an hour gets aggregated into an hourly partition. Hourly partitions gets rolled up into a daily partition. Several billion rows are processed like this monthly.
    The eventual method I've implemented is a cross between materialised views and GTTs. Instead of dropping or truncating the source partition and running an insert to repopulate it with the latest aggregated data, I wrote an API that allows you to give it the name of the destination table, the name of the partition to "refresh", and a SQL (that does the aggregation - kind of like the select part of a MV).
    It creates a brand new staging table using a CTAS, inspects the partitioned table, slaps the same indexes on the staging table, and then performs a partition exchange to replace the stale contents of the partition with that of the freshly build staging table.
    No expensive delete. No truncate that results in an empty and query-useless partition for several minutes while the data is refreshed.
    And any number of these partition refreshes can run in parallel.
    Why not use a GTT? Because they cannot be used in a partition exchange. And the cost of writing data into a GTT has to be weighed against the cost of using that data by writing it (or some of it) into permanent tables. Ideally one wants to plough through a data set once.
    Oracle has a fairly rich feature set - and these can be employed in all kinds of ways to get the job done.

  • Global temp table and edit

    Hi all,
    Can someone tell me why when I create a GTT and insert the data like the followijng ,I get insert 14 rows msg. But when I do a select statement from sqlwork shop , sometimes i get the data sometimes I don't. my understanding is this data is supposed to stay during my logon session then got cleaned out when I exit session.
    I am developing a screen in apex and will use this temp table for user to do some editing work. Once ithe editing is done then I save the data into a static table. Can this be done ? So far my every attempt to update the temp table always result to 0 rows updated and the temp table reversed back to 0 rows. CAn you help me ?
    CREATE GLOBAL TEMPORARY TABLE "EMP_SESSION"
    (     "EMPNO" NUMBER NOT NULL ENABLE,
         "ENAME" VARCHAR2(10),
         "JOB" VARCHAR2(9),
         "MGR" NUMBER,
         "HIREDATE" DATE,
         "SAL" NUMBER,
         "COMM" NUMBER,
         "DEPTNO" NUMBER
    ) ON COMMIT PRESERVE ROWS
    insert into emp_session( EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    select * from emp
    select * from emp_session
    -- sometimes I get 14 rows, sometimes 0 rows
    Thanks.
    Tai

    Tai,
    To say that Apex doesn't support GTT's is not quite correct. In order to understand why it is not working for you and how they may be of use in an Apex application, you have to understand the concept of a session in Apex as opposed to a conventional database session.
    In a conventional database session, as when you are connected with sqlplus then you have what is known as a dedicated session, or a synchronous connection. Temporary objects such as GTTs and packaged variables can persist across calls to the database. A session in Apex however is asynchronous by nature and a connection to the database is done through some sort of a server such as the Oracle HTTP server or the Apex Listener, which in effect maintains a pool of connections to the database and calls by your application aren't guaranteed to get the same connection for each call.
    To get over this, the guys who developed Apex came up with various methods to maintain session state and global objects that are persistent within the context of an Apex session. One of these is Apex collections, which are a device for maintaining collection like (array like) data that is persistent within an Apex session. These are Apex session specific objects in that they are local to the session that creates and maintains them.
    With this knowledge, you can then see why the GTT is not working for you and also how a GTT may be of use in an Apex application, provided you don't expect the data to persist across a call, as in a PL/SQL procedure. You should note though, that unless you are dealing with very large datasets, then a regular Oracle collection is preferable.
    I hope this explains your issue.
    Regards
    Andre

  • How to create a temp table in the memory, not in disk?

    in sql server, you can create a temp table in the memory instead of disk,
    then you can do the insert, delete,update and select on it.
    after finishing, just release it.
    in Oracle,
    I am wonderfing how to create a temp table in the memory, not in disk?
    thanks,

    Thanks for rectifying me Howard.
    I just read your full article on this too and its very well explained here:
    http://www.dizwell.com/prod/node/357
    Few lines from your article
    It is true, of course, that since Version 8.0 Oracle has provided the ability to create a Keep Pool in the Buffer Cache, which certainly sounds like it can do the job... especially since that word 'keep' is used again. But a keep pool is merely a segregated part of the buffer cache, into which you direct blocks from particular tables (by creating them, or altering them, with the BUFFER POOL KEEP clause). So you can tuck the blocks from such tables out of the way, into their own part of the buffer cache... but that is not the same thing as guaranteeing they'll stay there. If you over-populate the Keep Pool, then its LRU mechanism will kick in and age its contents out just as efficiently as an unsegregated buffer cache would.
    Functionally, therefore, there can be no guarantees. The best you can do is create a sufficiently large Keep Pool, and then choose the tables that will use it with care such that they don’t swamp themselves, and start causing each other to age out back to disk.
    Thanks and Regards

  • Best options to use in Temp Table

    Hello,
    I was just trying to figure out the best options we can choose with when we come across a scenario where we need to use a  Temp Table/Table Variable/Create
    a Temp Table on the fly.
    However, I could not see any big difference in using those options. As per my understanding using a table variable is more convenient if the query logic is
    small and the result set also will be comparatively small.Creating a temp table is also an easy option but it takes much time and we can not create any indexes on it. I am working on a query optimization task where in plenty of temp tables are used
    and the query takes more than five minutes to execute. We have created few indexes and all in few tables and reduced the query execution time up to 2 mnts.Can anyone give me more suggestions on it. I have gone through various articles about it and came to
    know that there is no one solution for this and I am aware of the basic criteria like  use Set No count on, Order the table in which the indexes are created, Do not use Select * instead use only columns which are really required, Create Indexes
    and all. Other than these I am stuck with the usage of temp tables. There are some limitations where I can convert all the Temp table logic to CTE (I am not saying its not possible, I really dont have time to spend for the conversion). Any suggestions are
    welcome.
    Actual Query
    select Code,dbo.GetTranslatedText(Name,'en-US')
    as Name from ProductionResponse.ProductionResponse
    00.00.02
    5225 rows
    With Table Variable
    DECLARE  @General
    TABLE(Code
    NVarchar(Max),Name
    NVarchar(Max)
    INSERT
    INTO @General
    select Code,dbo.GetTranslatedText(Name,'en-US')
    AS Name  from ProductionResponse.ProductionResponse
    select
    * from @General
    00.00.03
    5225 rows
    With an Identity Column
    DECLARE  @General
    TABLE(Id
    INT IDENTITY(1,1)
    ,Code NVarchar(Max),Name
    NVarchar(Max)
    INSERT
    INTO @General
    select Code,dbo.GetTranslatedText(Name,'en-US')
    AS Number  from ProductionResponse.ProductionResponse
    select
    * from @General
    00.00.04
    5225 rows
    With Temp Table:
    CREATE
    TABLE #General (Id
    INT IDENTITY(1,1)
    PRIMARY KEY,Code
    NVarchar(Max),Name
    NVarchar(Max)
    INSERT
    INTO #General
    select Code,dbo.GetTranslatedText(Name,'en-US')
    as Name from ProductionResponse.ProductionResponse
    select
    * from #General
    DROP
    TABLE #General
    00.00.04
    5225 rows
    With Temp Table on the Fly
    SELECT G.Code,G.Name
    INTO #General  
    FROM
    select Code,dbo.GetTranslatedText(Name,'en-US')
    as Name from ProductionResponse.ProductionResponse
    )G
    select
    * from #General
    00.00.04
    5225 rows

    >> I was just trying to figure out the best options we can choose with when we come across a scenario where we need to use a Temp Table/Table Variable/Create a Temp Table on the fly. <<
    Actually, we want to avoid all of those things in a declarative/functional language. The goal is to write the solution in a single statement. What you are doing is mimicking a scratch tape in a 1950's tape file system. 
    Another non-declarative technique is to use UDFs, to mimic 1950's procedural code or OO style methods. Your sample code is full of COBOL-isms! In RDBMS we follow ISO-11179 rules, so we have “<something in particular>_code” rather than just “code” like
    a field within a COBOL record. The hierarchical record structure provides context, but in RDBMS, data elements are global.  Or better, they are universal names. 
    >> I am aware of the basic criteria like use SET NO COUNT ON, Order the table in which the indexes are created, Do not use SELECT * instead use only columns which are really required, CREATE INDEXes and all.<<
    All good, but you missed others. Never use the same name for a data element (scalars) and a table (sets). Think about what things like “ProductionResponse.production_response” means. A set with one element is a bit weird, but that is what you said. Also, what
    is this response? A code? A count? It lacks what we call an attribute property. 
    This was one of the flaws we inherited when ANSI standardized SQL and we should have fixed it. Oh well, too late now. 
    Never use NVARCHAR(MAX). Why do you need to put all of the Soto Zen sutras in Chinese Unicode? When you use over-sized data elements, you eventually get garbage data. 
    >> Other than these I am stuck with the usage of temp tables. There are some limitations where I can convert all the Temp table logic to CTE (I am not saying its not possible, I really do not have time to spend for the conversion). Any suggestions are
    welcome.<<
    Yes! This is how we do declarative/functional programming! Make the effort, so the optimizer can work, so you can use parallelism and so you can port your code out of T-SQL dialect. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Temp Table in view

    I Know we cannot use Temp table,table variable in View but i want to know the reason behind it

    Assuming the second batch is executed from a 2nd connection, there is no doubt that the query should return 46 on that 2nd connection. If the 1st connection would run the same SELECT statement, it should return 33.
    And if the definition of the temp tables are
    CREATE TABLE #temp(a int NOT NULL)
    CREATE TABLE #temp(b float NOT NULL)
    Keep in mind how view definitions are stored in SQL Server.
    I don't know exactly why the original poster wanted this, but what does make sense is of course a temporary view, and preferrably one that does not require a batch of its own. A couple of years ago, I wrote a stored procedure where I found that I repeated
    the same conditions all over again. This made me year for something like a module-level CTE and I submitted this Connect item:
    http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=343067
    Erland Sommarskog, SQL Server MVP, [email protected]

  • MS SQL Server 2014: Error inserting into Temp table with index and identity field

    In this thread, I mentioned a problem with SQL Server 2014:
    SQL Server 2014: Bug with IDENTITY INSERT ON
    The question was answered, it is a bug. To keep you informed on this issue, I open this discussion.
    Problem:
    The code below works perfectly fine on MS SQL Server 2008 R2 and MS SQL Server 2012, but gives an error every second time the proc is executed on MS SQL Server 2014. If I do not define any index on the temp table, the problem disappears. Defining the index
    after the insert, does not help.
    SET NOCOUNT ON
    GO
    IF EXISTS (SELECT 1 FROM sys.procedures WHERE name = 'usp_Test') DROP PROC dbo.usp_Test;
    GO
    CREATE PROC dbo.usp_Test AS
    BEGIN
    SET NOCOUNT ON
    CREATE TABLE #Source(ID integer NOT NULL);
    INSERT INTO #Source VALUES (1), (2), (3);
    CREATE TABLE #Dest (ID integer IDENTITY(1,1) NOT NULL);
    CREATE INDEX #IDX_Dest ON #Dest (ID);
    PRINT 'Check if the insert might cause an identity crisis';
    SELECT 'Source' AS SourceTable, * FROM #Source;
    SELECT 'Destination' AS DestTable, * FROM #Dest;
    SET IDENTITY_INSERT #Dest ON;
    PRINT 'Do the insert';
    INSERT INTO #Dest (ID) SELECT ID FROM #Source;
    PRINT 'Insert ready';
    SET IDENTITY_INSERT #Dest OFF;
    SELECT * FROM #Dest;
    DROP TABLE #Source;
    DROP TABLE #Dest;
    END;
    GO
    PRINT 'First execution of the proc, everything OK';
    EXEC dbo.usp_Test;
    PRINT '';
    PRINT 'Second execution of the proc, the insert fails.';
    PRINT 'Removing the index #IDX_Dest causes the error to disappear.';
    EXEC dbo.usp_Test;
    GO
    DROP PROC dbo.usp_Test;
    GO

    There is some progress. Communication from a former Microsoft employee tells us this:
    Shivendra Vishal
    Engineer at Microsoft
    I am no longer with MS, and I do not have code access, however from the public symbols, I could make out following:
    sqlmin!SetidentI2I4+0x1f3:
    000007fe`f4d865d3 488b10 mov rdx,qword ptr [rax] ds:00000000`00000000=????????????????
    ExceptionAddress: 000007fef4d865d3 (sqlmin!SetidentI2I4+0x00000000000001f3)
    ExceptionCode: c0000005 (Access violation)
    ExceptionFlags: 00000000
    NumberParameters: 2
    Parameter[0]: 0000000000000000
    Parameter[1]: 0000000000000000
    Attempt to read from address 0000000000000000
    This is a read AV and from registers it is clear that we were trying to move the value of location pointed by qword of register rax which is not valid:
    rax=0000000000000000 rbx=0000000000000038 rcx=0000000000001030
    rdx=0000000000000006 rsi=00000001f55def98 rdi=00000000106fd070
    rip=000007fef4d865d3 rsp=00000000106fcf40 rbp=00000000106fcfe9
    r8=0000000000000000 r9=00000001f55def60 r10=00000001f55defa0
    r11=00000000106fcd20 r12=0000000000000000 r13=0000000000000002
    r14=00000001f49c3860 r15=00000001f58c0040
    iopl=0 nv up ei pl nz na po nc
    cs=0033 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010206
    The stack is:
    # Child-SP RetAddr Call Site
    00 00000000`106fcf40 000007fe`f30c1437 sqlmin!SetidentI2I4+0x1f3
    01 00000000`106fd050 000007fe`f474e7ce sqlTsEs!CEsExec::GeneralEval4+0xe7
    02 00000000`106fd120 000007fe`f470e6ef sqlmin!CQScanUpdateNew::GetRow+0x43d
    03 00000000`106fd1d0 000007fe`f08ff517 sqlmin!CQueryScan::GetRow+0x81
    04 00000000`106fd200 000007fe`f091cebe sqllang!CXStmtQuery::ErsqExecuteQuery+0x36d
    05 00000000`106fd390 000007fe`f091ccb9 sqllang!CXStmtDML::XretDMLExecute+0x2ee
    06 00000000`106fd480 000007fe`f08fa058 sqllang!CXStmtDML::XretExecute+0xad
    07 00000000`106fd4b0 000007fe`f08fb66b sqllang!CMsqlExecContext::ExecuteStmts<1,1>+0x427
    08 00000000`106fd5f0 000007fe`f08fac2e sqllang!CMsqlExecContext::FExecute+0xa33
    09 00000000`106fd7e0 000007fe`f152cfaa sqllang!CSQLSource::Execute+0x86c
    0a 00000000`106fd9b0 000007fe`f152c9e8 sqllang!CStmtExecProc::XretLocalExec+0x25a
    0b 00000000`106fda30 000007fe`f152a1d8 sqllang!CStmtExecProc::XretExecExecute+0x4e8
    0c 00000000`106fe1e0 000007fe`f08fa058 sqllang!CXStmtExecProc::XretExecute+0x38
    0d 00000000`106fe220 000007fe`f08fb66b sqllang!CMsqlExecContext::ExecuteStmts<1,1>+0x427
    0e 00000000`106fe360 000007fe`f08fac2e sqllang!CMsqlExecContext::FExecute+0xa33
    0f 00000000`106fe550 000007fe`f0902267 sqllang!CSQLSource::Execute+0x86c
    10 00000000`106fe720 000007fe`f0909087 sqllang!process_request+0xa57
    11 00000000`106feee0 000007fe`f2bf49d0 sqllang!process_commands+0x4a3
    12 00000000`106ff200 000007fe`f2bf47b4 sqldk!SOS_Task::Param::Execute+0x21e
    13 00000000`106ff800 000007fe`f2bf45b6 sqldk!SOS_Scheduler::RunTask+0xa8
    14 00000000`106ff870 000007fe`f2c136ff sqldk!SOS_Scheduler::ProcessTasks+0x279
    15 00000000`106ff8f0 000007fe`f2c138f0 sqldk!SchedulerManager::WorkerEntryPoint+0x24c
    16 00000000`106ff990 000007fe`f2c13246 sqldk!SystemThread::RunWorker+0x8f
    17 00000000`106ff9c0 000007fe`f2c13558 sqldk!SystemThreadDispatcher::ProcessWorker+0x3ab
    18 00000000`106ffa70 00000000`775d59ed sqldk!SchedulerManager::ThreadEntryPoint+0x226
    19 00000000`106ffb10 00000000`7780c541 kernel32!BaseThreadInitThunk+0xd
    1a 00000000`106ffb40 00000000`00000000 ntdll!RtlUserThreadStart+0x21
    Unassembling the function:
    000007fe`f4d8658e 4c8b10 mov r10,qword ptr [rax]
    000007fe`f4d86591 4533e4 xor r12d,r12d
    000007fe`f4d86594 410fb7d5 movzx edx,r13w
    000007fe`f4d86598 4533c9 xor r9d,r9d
    000007fe`f4d8659b 4533c0 xor r8d,r8d
    000007fe`f4d8659e 488bc8 mov rcx,rax
    000007fe`f4d865a1 4489642420 mov dword ptr [rsp+20h],r12d
    000007fe`f4d865a6 41ff5230 call qword ptr [r10+30h]
    000007fe`f4d865aa 8b5597 mov edx,dword ptr [rbp-69h]
    000007fe`f4d865ad 4c8b10 mov r10,qword ptr [rax]
    000007fe`f4d865b0 4489642438 mov dword ptr [rsp+38h],r12d
    000007fe`f4d865b5 4489642430 mov dword ptr [rsp+30h],r12d
    000007fe`f4d865ba 458d442401 lea r8d,[r12+1]
    000007fe`f4d865bf 4533c9 xor r9d,r9d
    000007fe`f4d865c2 488bc8 mov rcx,rax
    000007fe`f4d865c5 c644242801 mov byte ptr [rsp+28h],1
    000007fe`f4d865ca 4488642420 mov byte ptr [rsp+20h],r12b
    000007fe`f4d865cf 41ff5250 call qword ptr [r10+50h]
    000007fe`f4d865d3 488b10 mov rdx,qword ptr [rax] <=================== AV happened over here
    000007fe`f4d865d6 488bc8 mov rcx,rax
    000007fe`f4d865d9 4c8bf0 mov r14,rax
    000007fe`f4d865dc ff5268 call qword ptr [rdx+68h]
    000007fe`f4d865df 488d55e7 lea rdx,[rbp-19h]
    000007fe`f4d865e3 4c8b00 mov r8,qword ptr [rax]
    000007fe`f4d865e6 488bc8 mov rcx,rax
    000007fe`f4d865e9 41ff5010 call qword ptr [r8+10h]
    000007fe`f4d865ed f6450a04 test byte ptr [rbp+0Ah],4
    I remember few issues with scan2ident function, I am not sure if they have fixed it however it appears that this is intoduced to SQL 2014 and we need help from MS to get this resolved as it needs code analysis.
    It is not getting simulated for other versions of SQL apart from SQL 2014.
    Also to add, interestingly, the value of rax is not visibly changed and it was successfully passed on to rcx, which has a valid value, so something should have changed the value of rax inside call to function using call qword ptr [r10+50h], and looking at this
    it appears that it might be a list of functions and we are going at particular offset [50h]. So, bottom line is that the call to function qword ptr [r10+50h], should be changing something in rax, and debugging/analyzing this code might give us some more idea.

  • Does a temp table is reuired to insert into a table

    Hi ,
    I am using a stored procedure to check the availability of a record in a table and deleting the record if exists ,
    actually  if the user have multiple record i need to delete and store it in removed table  , so i used insert with select command to insert into the table , do i need to use a temp table to insert multiple record in removed table .
    Thank You
    Jeevan Vinay

    No, it doesn't need to be that complex.
    The records need to go to your deleted/history table, and they also need to be deleted from the main table. I would just insert the records into the history table and delete the records from your main table by joining back to it on the delete with the PK.
    You could try something like this:
    CREATE TABLE ##main_table (employee_id INT IDENTITY(1,1), employee_name VARCHAR(50))
    CREATE TABLE ##history_table (employee_id INT, employee_name VARCHAR(50))
    INSERT INTO ##main_table (employee_name)
    SELECT 'Alice'
    UNION ALL
    SELECT 'Bob'
    UNION ALL
    SELECT 'Charlie'
    --Bob is the user that will get deleted (employee_id = 2)
    --Insert record into history table
    INSERT INTO ##history_table
    SELECT *
    FROM ##main_table
    WHERE employee_id = 2
    --Delete record from main table
    DELETE m
    FROM ##main_table m
    JOIN ##history_table h
    ON m.employee_id = h.employee_id
    SELECT *
    FROM ##history_table
    SELECT *
    FROM ##main_table

  • Temp Table in Package returning Ref_Cursor?

    I'm new to Oracle. Here is what I'm trying to do.
    I need to lookup all records with a certain ID. The IDs are stored by quarter and year. I'm trying to compare records with the previous 3 quarters.
    so record with ID = 1 also has Qtr = 1, Year = 2008.
    I would also need to find all ID's for the previous 3 quarters ( Q 4 of 2007, Q 3 of 2007, and Q 2 of 2007).
    I'm trying to write a package that will return a ref cursor with all 4 ids so the output would look like a table with 4 rows and 1 column.
    In SQL Server I could create a temp table, insert these 4 values in and return a Select * From TempTable.
    How can I accomplish this in Oracle 10g?

    Something like this ?
    test@ORA10G>
    test@ORA10G> drop table tblyearquarter;
    Table dropped.
    test@ORA10G>
    test@ORA10G> create table tblyearquarter (id, qtr, yr, createdate) as
      2  select
      3    round(dbms_random.value(1,10000)),
      4    t1.qtr,
      5    t2.yr,
      6    (sysdate - t3.indx)
      7  from
      8  (select level+2003 as yr from dual connect by level<=5) t2,
      9  (select level as qtr from dual connect by level<=4) t1,
    10  (select level as indx from dual connect by level<=round(dbms_random.value(1,4))) t3;
    Table created.
    test@ORA10G>
    test@ORA10G> select * from tblyearquarter;
            ID        QTR         YR CREATEDAT
          5059          1       2004 09-MAR-08
          6619          1       2004 08-MAR-08
          5776          1       2004 07-MAR-08
          6943          2       2004 09-MAR-08
          4338          2       2004 08-MAR-08
          8568          2       2004 07-MAR-08
          5878          3       2004 09-MAR-08
          2675          3       2004 08-MAR-08
          4667          3       2004 07-MAR-08
            40          4       2004 09-MAR-08
          1400          4       2004 08-MAR-08
          9509          4       2004 07-MAR-08
          6628          1       2005 09-MAR-08
          4356          1       2005 08-MAR-08
          2439          1       2005 07-MAR-08
          7094          2       2005 09-MAR-08
           482          2       2005 08-MAR-08
          8596          2       2005 07-MAR-08
          4855          3       2005 09-MAR-08
          4447          3       2005 08-MAR-08
          3341          3       2005 07-MAR-08
          5220          4       2005 09-MAR-08
          8461          4       2005 08-MAR-08
          2746          4       2005 07-MAR-08
          3561          1       2006 09-MAR-08
           241          1       2006 08-MAR-08
           108          1       2006 07-MAR-08
          3605          2       2006 09-MAR-08
           310          2       2006 08-MAR-08
           939          2       2006 07-MAR-08
          6611          3       2006 09-MAR-08
          5679          3       2006 08-MAR-08
          3975          3       2006 07-MAR-08
          2238          4       2006 09-MAR-08
          7323          4       2006 08-MAR-08
          8104          4       2006 07-MAR-08
          3206          1       2007 09-MAR-08
          7420          1       2007 08-MAR-08
          7386          1       2007 07-MAR-08
          4237          2       2007 09-MAR-08
          9329          2       2007 08-MAR-08
          6105          2       2007 07-MAR-08
          3800          3       2007 09-MAR-08
          3967          3       2007 08-MAR-08
          8200          3       2007 07-MAR-08
           463          4       2007 09-MAR-08
          9518          4       2007 08-MAR-08
          1451          4       2007 07-MAR-08
          9541          1       2008 09-MAR-08
          1380          1       2008 08-MAR-08
          9320          1       2008 07-MAR-08
          9720          2       2008 09-MAR-08
          4681          2       2008 08-MAR-08
          6431          2       2008 07-MAR-08
          9586          3       2008 09-MAR-08
          8620          3       2008 08-MAR-08
          6859          3       2008 07-MAR-08
          5883          4       2008 09-MAR-08
           548          4       2008 08-MAR-08
          4647          4       2008 07-MAR-08
    60 rows selected.
    test@ORA10G>
    test@ORA10G> select id, qtr, yr
      2    from (select id, qtr, yr, rownum as rnum
      3            from (select id, qtr, yr, createdate
      4                    from (select id,
      5                                 qtr,
      6                                 yr,
      7                                 createdate,
      8                                 row_number() over(partition by yr, qtr order by createdate desc) as seq
      9                            from tblyearquarter)
    10                   where seq = 1
    11                   order by yr desc, qtr desc)
    12           where yr || qtr <= &year || &quarter)
    13   where rnum <= 4;
    Enter value for year: 2008
    Enter value for quarter: 1
    old  12:          where yr || qtr <= &year || &quarter)
    new  12:          where yr || qtr <= 2008 || 1)
            ID        QTR         YR
          9541          1       2008
           463          4       2007
          3800          3       2007
          4237          2       2007
    test@ORA10G>
    test@ORA10G> /
    Enter value for year: 2007
    Enter value for quarter: 3
    old  12:          where yr || qtr <= &year || &quarter)
    new  12:          where yr || qtr <= 2007 || 3)
            ID        QTR         YR
          3800          3       2007
          4237          2       2007
          3206          1       2007
          2238          4       2006
    test@ORA10G>
    test@ORA10G> /
    Enter value for year: 2006
    Enter value for quarter: 2
    old  12:          where yr || qtr <= &year || &quarter)
    new  12:          where yr || qtr <= 2006 || 2)
            ID        QTR         YR
          3605          2       2006
          3561          1       2006
          5220          4       2005
          4855          3       2005
    test@ORA10G>
    test@ORA10G>pratz

Maybe you are looking for

  • How can I cause the images to become clear like on Internet Explorer?

    When using IE if a picture is blurred I can right click the picture and click on "Display Image with Full Quality." Or if all pictures on the page are blurred I can right click on the page and click on "Display all Images with Full Quality." These op

  • How to store a RSA pair key in Java Key Store (jks) and VS

    Hi Everyone , I have generated a RSA pair key . now I need to store my public key in a Java Key Store (.jks file) . and then I need to read this .jks file in another application and get this public key to use for verification . I'll appreciate it if

  • What to Dump When MBA Disc Full?

    My MBA (10.6.8) has 60 GB of memory. Only 7+GB available, and have occasionally get warning about start-up disk being full. I've deleted entire iMusic library and Pictures is down to less than a GB. What else can I delete or reduce? Doesn't seem I ca

  • "Customize Toolbar" Not Appearing

    Selecting "Customize Toolbar" does not work correctly in my Intel iMac (10.6.7), with Snow Leopard. The drop down menu of available customizing options does not appear. How can this be corrected?

  • How to add BusinessPartner using DI server?

    Hi expert,      previous i used DI API  for BP and Sales Order Add.Now i want to add  BP and SalesOrder using DI server.Please help any expert ,      1 How to add BusinessPartner with address using DI server ?      2 How to add Sales Order using DI s