Bug in Entity Framework: No rows returned with criteria.

Bug: Oracle fails to return rows with lambda criteria on string field from varchar2 column in view.
Steps to reproduce:
Create view:
CREATE OR REPLACE VIEW "PHILIP_TEST" ("ROWNUMBER", "DRIVER") AS
SELECT
     ROWNUMBER,
     DECODE(DRIVER,CHR(2),NULL,DRIVER) DRIVER
FROM FLIGHT
WHERE SCHEDULEDDATE = TRUNC(SYSDATE);
Rownumber is unique key (number), Driver is varchar2(7).
Create C# console application in VS2010
Add Entities Model and add view.
Add this code to Main()
var context = new Entities();
// Test code start
var allrows = context.PHILIP_TEST.Where(x => x.DRIVER != null).ToArray();
Console.WriteLine(allrows.Count());
// Select first driver as criteria
var driver = allrows[0].DRIVER;
Console.WriteLine(driver);
// Test code end
// This line fails to return any rows
var result = context.PHILIP_TEST.Where(x => x.DRIVER == driver).ToArray();
Console.WriteLine(result.Count());
Console.ReadLine();
Add some test data to flight.
Run it!
The expression with criteria x.DRIVER == driver should return at least 1 row. It doesnt.
Running the following from SQL Developer returns records: Conclution the view is fine.
SELECT * FROM PHILIP_TEST WHERE DRIVER = 'MJA'
If definition of DRIVER column in view is changed from: "DECODE(DRIVER,CHR(2),NULL,DRIVER) DRIVER" to just "DRIVER", then code returns rows as expected.

are you sure your two select statements can't be combined to one query with outer join?
if the outer join is possible, after creating the query, it will have one group with all the fields/columns you selected.
drag the columns you selected in the personal info, outside the group.
this should enable you to have one query with two groups, a master (personal info) and a detail (monetary calculations).
your first frame will have the master group as source, while for the second the detail. now, the "Value if Null" should work.
if the outer join is not possible,
create one query with only the personal info. in the group, create column formula to get the monetary columns (you may need to create place holders if selecting multiple columns)
drag the columns you selected in the personal info, outside the group.
this should enable you to have one query with two groups, a master (personal info) and a detail (monetary calculations, you CF_ and CP_ columns).
your first frame will have the master group as source, while for the second the detail. now, the "Value if Null" should work in your CF_ and CP_ columns

Similar Messages

  • Entity Framework - Execute Stored Procedures With Table Valued Patameter

    How to pass a table valued parameter to a stored procedure in Entity Framework using ExecuteSqlCommand or SqlQuery method?
    Following is my code - 
    DataTable dataTable=new DataTable();
    dataTable.Columns.Add("col1", typeof(int));
    dataTable.Columns.Add("col2", typeof(bool));
    dbContext.Database.ExecuteSqlCommand("exec stored_proc @tvp",
                            new SqlParameter() { SqlDbType = SqlDbType.Structured, ParameterName = "@tvp", Value = dataTable }
    This throws an exception saying 'The table type parameter '@tvp' must have a valid type name.'

    You must set the TypeName property of the SqlParameter to the name of your table type that you have defined in the database:
    SqlParameter param = new SqlParameter();
    param.SqlDbType = SqlDbType.Structured;
    param.ParameterName = "@tvp";
    param.TypeName = "dbo.YourTableType";
    param.Value = dataTable;
    dbContext.Database.ExecuteSqlCommand("exec stored_proc @tvp", param);
    Of course you must define the table type in the database first:
    CREATE TYPE dbo.YourTableType AS TABLE
    ( col1 int, col1 bit )
    Please remember to the following page on MSDN for more information:
    https://msdn.microsoft.com/en-us/library/bb675163(v=vs.110).aspx
    Hope that helps.
    Please also remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

  • No rows returned with where number_value

    Hi all,
    Im using Oracle 10.2.0.1 on Windows 2000.
    I got something strange here.
    I have a table like:
    TABLE_NAME                     COLUMN_NAME                    DATA_TYPE        DATA_LENGTH DATA_PRECISION DATA_SCALE
    TEST                           COL1                           NUMBER                    22           1     0when I try to perform a query like:
    select * from test where col = 0this returns 0 rows.
    when I do:
    select * from test;
          COL1
             1
             1
             1
             1
             0
             0
             2but when a use to_number, it returns rows for zero value:
    select * from test where to_number(col) = 0;
          COL1
             0
             0somebody knows about this strange problem?
    thank you very much!!!!
    []´s

    Hi,
    >>I´m trying to understand this.
    Me too ;-)
    SQL> create table test (col1 number);
    Table created.
    SQL> alter table test add constraint ck_test check (col1 in ('0','1'));
    Table altered.
    SQL> insert into test values (0);
    1 row created.
    SQL> select * from test where col1=0;
    no rows selected
    SQL> explain plan for select * from test where col1=0;
    Explained.
    SQL> set linesize 130
    SQL> set pagesize 0
    SQL> select * from table(dbms_xplan.display);
    Plan hash value: 766971379
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |      |     1 |    13 |     0   (0)|          |
    |*  1 |  FILTER            |      |       |       |            |          |
    |*  2 |   TABLE ACCESS FULL| TEST |     1 |    13 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
    1 - filter(NULL IS NOT NULL)
       2 - filter("COL1"=0)
    Note
       - dynamic sampling used for this statement
    19 rows selected.
    SQL> select * from test where to_char(col1)=0;
          COL1
             0
    SQL> explain plan for select * from test where to_char(col1)=0;
    Explained.
    SQL> set linesize 130
    SQL> set pagesize 0
    SQL> select * from table(dbms_xplan.display);
    Plan hash value: 1357081020
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |      |     1 |    13 |     3   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS FULL| TEST |     1 |    13 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
    1 - filter(TO_NUMBER(TO_CHAR("COL1"))=0)
    Note
       - dynamic sampling used for this statement
    17 rows selected.Cheers
    Legatti

  • Getting the number of rows returned from ResultSet

    Hi,
    Does anyone know a method to get the number of rows returned with a query using the Resultset class?
    Thanks.

    Hi 281080,
    If your database and JDBC driver support it, in order to use the solution that da-alexj has suggested, you need to create a 'scrollable' "ResultSet" -- the javadoc for method "createStatement()" (in class "java.sql.Connection") has more details.
    However, I have found with Oracle 8.1.7.4 database and Oracle (thin) JDBC driver, that part of their implementation of the "last()" method (in class "java.sql.ResultSet") is to actually iterate through the entire "ResultSet" in order to reach the last row. If your "ResultSet" is very large (I tested it with a 100,000 row "ResultSet"), this will take a long time.
    Just wanted to make you aware of that.
    Of-course, this may be irrelevant to you since I didn't see any mention in your post of what database and JDBC driver you are using.
    Hope this has helped you, anyway.
    Good Luck,
    Avi.

  • Sorting is wrong with Entity Framework for oracle

    Hi,
    I've downloaded the Entity Framework for Oracle beta and I found a bug. It's easy to repro:
    - Create a model with a simple table
    - Create a dynamic data web app
    - display the content of your table and try to sort
    -> the sql generated is wrong and only sorts on the currently displayed rows and not the entire data.
    Did anyone else notice that?
    Edited by: lnu on 14 févr. 2011 05:51

    Before ODP.NET beta with EF was available I was working with OracleEFProvider from CodePlex (sample alpha version but works with VS2010).
    I found the same issue there. Since I had a source code I managed to find the solution.
    In class which implemented the base class DbExpressionVisitor there was a method: public override ISqlFragment Visit(DbSkipExpression e)
    I had to add sort clause AFTER visiting the expression (which was done too early in previous code).
    As the main idea of DbExpressionVisitor should be the same in case of Oracle provider, this can be the reason of improper sorting in queries with paging.

  • Using Entity Framework with SQL Azure - Reliability

    (This is a cross post from http://stackoverflow.com/questions/5860510/using-entity-framework-with-sql-azure-reliability since I have yet to receive any replies there)
    I'm writing an application for Windows Azure. I'm using Entity Framework to access SQL Azure. Due to throttling and other mechanisms in SQL Azure, I need to make sure that my code performs retries if an SQL statement has failed. I'm trying to come up with
    a solid method to do this.
    (In the code below, ObjectSet returns my EFContext.CreateObjectSet())
    Let's say I have a function like this:
      public Product GetProductFromDB(int productID)
         return ObjectSet.Where(item => item.Id = productID).SingleOrDefault();
    Now, this function performs no retries and will fail sooner or later in SQL Azure. A naive workaround would be to do something like this:
      public Product GetProductFromDB(int productID)
         for (int i = 0; i < 3; i++)
            try
               return ObjectSet.Where(item => item.Id = productID).SingleOrDefault();
            catch
    Of course, this has several drawbacks. I will retry regardless of SQL failure (retry is waste of time if it's a primary key violation for instance), I will retry immediately without any pause and so on.
    My next step was to start using the Transient Fault Handling library from Microsoft. It contains RetryPolicy which allows me to separate the retry logic from the actual querying code:
      public Product GetProductFromDB(int productID)
         var retryPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(5);
         var result = _retryPolicy.ExecuteAction(() =>
               return ObjectSet.Where(item => item.Id = productID).SingleOrDefault;
         return result;
    The latest solution above is described as ahttp://blogs.msdn.com/b/appfabriccat/archive/2010/10/28/best-practices-for-handling-transient-conditions-in-sql-azure-client-applications.aspx Best Practices for Handling Transient Conditions in SQL Azure Client
    Application (Advanced Usage Patterns section).
    While this is a step forward, I still have to remember to use the RetryPolicy class whenever I want to access the database via Entity Framework. In a team of several persons, this is a thing which is easy to miss. Also, the code above is a bit messy in my
    opinion.
    What I would like is a way to enforce that retries are always used, all the time. The Transient Fault Handling library contains a class called ReliableSQLConnection but I can't find a way to use this with Entity Framework.
    Any good suggestions to this issue?

    Maybe some usefull posts
    http://blogs.msdn.com/b/appfabriccat/archive/2010/12/11/sql-azure-and-entity-framework-connection-fault-handling.aspx
    http://geekswithblogs.net/iupdateable/archive/2009/11/23/sql-azure-and-entity-framework-sessions-from-pdc-2009.aspx

  • Seeding multiple databases with single Entity Framework context

    I am developing a single-instance, multi-tenant web application, with a SQL database using Entity Framework 6 Code-First. 
    I want to have a separate database for each client, generated from the same EF models, with a single DbContext. The database to connect to will be determined by the subdomain that the client is using the web app from. 
    This seems to work fine and the correct database is connected to depending on the subdomain. However my issue is seeding the databases with data. This is the code I have:
    foreach (var connString in ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>()))
    Configuration.PerformDatabaseMigration(connString.Name);
    This then calls the PerformDatabaseMigration method: 
    public class Configuration : DbMigrationsConfiguration<DataContext>
    public Configuration()
    AutomaticMigrationsEnabled = false;
    AutomaticMigrationDataLossAllowed = false;
    public static void PerformDatabaseMigration(string connStringName)
    var databaseInitialiser = new Configuration { TargetDatabase = new DbConnectionInfo(connStringName) };
    var dbMigrator = new DbMigrator(databaseInitialiser);
    dbMigrator.Update();
    protected override void Seed(DataContext context)
    base.Seed(context);
    var superAdmin = new User { Id = 1, UserName = "SuperAdmin" };
    context.Users.AddOrUpdate(superAdmin);
    The issue is that when seeding this data for the second database, the context passed into the Seed method already has the admin user added to the `DbSet<User>` property of the context, even though the context is for the second databse connection, not
    the first. It appears that the context is not being cleared from seeding the first database, and so I receive a `DbUpdateException`, as my User.Username field is a unique index.
    Cannot insert duplicate key row in object 'dbo.Users' with unique index 'IX_UserName'. The duplicate key value is (SuperAdmin).\r\nThe statement has been terminated.
    public class User : ModelBase, IUserIdentity, IPrincipal, IIdentity 
        [Index(IsUnique = true)]     
      [Required]     
      [StringLength(40)]       
    public string UserName { get; set; }

    Hello Attune,
    >>This seems to work fine and the correct database is connected to depending on the subdomain. However my issue is seeding the databases with data.
    Is that you firstly create these databases and then call the PerformDatabaseMigration method to seed these database with data? Do you have a try to seed these database data when creating the database with AutomaticMigrationsEnabled = true; with your provided
    configuration class, I tested it and it could work as seeding same data to different database:
    internal sealed class Configuration : DbMigrationsConfiguration<CFs.CFContext>
    public Configuration()
    AutomaticMigrationsEnabled = true;
    public static void PerformDatabaseMigration(string connStringName)
    var databaseInitialiser = new Configuration { TargetDatabase = new DbConnectionInfo(connStringName) };
    var dbMigrator = new DbMigrator(databaseInitialiser);
    dbMigrator.Update();
    protected override void Seed(CFs.CFContext context)
    base.Seed(context);
    var superAdmin = new ApplicationUser() { ApplicationUserID = 1, FirstName = "", LastName = "" };
    context.ApplicationUsers.AddOrUpdate(superAdmin);
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Entity framework-calling stored Proc to return one param returns ORA-6550

    Hi There,
    I am new to the VS2010/MVC3 game with ODP.net, so no abuse please .......
    I have successfully inserted a record into a table via the controller/entity framework, but only by currently hard coding the id. The next logical step is to attempt to obtain the id from the Oracle DB via a stored procedure. Here is the body of the PL/SQL procedure on the Oracle side:-
    create or replace package body dotnetcommon as
    PROCEDURE getnextpoid ( p_to_id OUT NUMBER ) IS
    BEGIN
         SELECT pord_seq.nextval INTO p_to_id FROM dual;
    END getnextpoid;
    end dotnetcommon;
    show error
    I have then added this procedure to my Entity Framework Model within VS2010 , and from within the Model Browser, I now have a stored procedure of "DOTNETCOMMON_GETNEXTPOID" under my Model.Store. This has an out type parameter named p_to_id, which is a type of number.
    I then added a function import, so I have a function by the name of "GETNEXTPOID" under the Function Imports folder, with a collection property of 'None'.
    This function has a parameter P_TO_ID with a type of "Decimal".
    From within my controller, I have the following code:-
    [HttpPost]
    public string Create(PURCHASEORDER po)
    TasEntities tmprep = new TasEntities();
    ObjectParameter poid = new ObjectParameter("poId", typeof(Int16));
    var result = tmprep.GETNEXTPOID(poid);
    return "Next PO Id is " + result;
    Thus, on pressing the Save from my view, i am hoping to return the next logical sequence number into the poid objectparameter. However, I am presented with the following error:-
    Inner Exception of:-
    {"ORA-06550: line 1, column 8:\nPLS-00306: wrong number or types of arguments in call to 'GETNEXTPOID'\nORA-06550: line 1, column 8:\nPL/SQL: Statement ignored"}
    It falls over , taking me to the Model.Designer.cs at :-
    public int GETNEXTPOID(ObjectParameter p_TO_ID)
    return base.ExecuteFunction("GETNEXTPOID", p_TO_ID);
    I am assuming it is to do with the decimal/int/number conversion, but I do not have the nouse to fix it ? Does anybody know what is wrong with what I have attempted to do above ?
    Please please get back to me if you need any more information, I am wanting to move on but cannot.
    I have seen posts regarding setting the sequence in a before insert trigger on the table, but this is not ideal. Can the above not work instead ?
    Many thanks in advance for any help you can provide.
    Graeme
    Edited by: user4487499 on 05-Apr-2011 08:18

    I have now raised this in the odp.net forum, as on looking at other posts it seems to be the best place for it.
    Cheers,
    Graeme
    Edited by: user4487499 on 05-Apr-2011 08:18
    Edited by: user4487499 on 05-Apr-2011 13:00

  • Entity Framework : A short way to copy one object with it's child to a new object ?

    Hello !
    I'm using entity framework 6.
    Sometimes I need to copy an existing object with all its childs to a new object and to save to database.
    I'm using a standart way by creating a new object , copy one by one it's properties from existing object ( except the ID ) , after I create new object for every child and copy one by one each properties except the ID and Parent id......
    But of course this is a hard way to do especially when the object have a lot's of properties.
    I want to know is there any short way  ( built in) to do this ?
    Thank you !

    Actually , I'm using this extension :
    Imports System.ComponentModel
    Imports System.Collections
    Imports System.Data.Entity.Core.Objects.DataClasses
    Imports System.Runtime.Serialization
    Imports System.IO
    Imports System.Reflection
    Module Extensions
    <System.Runtime.CompilerServices.Extension> _
    Public Function Clone(Of T As EntityObject)(source As T) As T
    Dim ser = New DataContractSerializer(GetType(T))
    Using stream = New MemoryStream()
    ser.WriteObject(stream, source)
    stream.Seek(0, SeekOrigin.Begin)
    Return CType(ser.ReadObject(stream), T)
    End Using
    End Function
    <System.Runtime.CompilerServices.Extension> _
    Public Function ClearEntityReference(source As EntityObject, bCheckHierarchy As Boolean) As EntityObject
    Return source.ClearEntityObject(bCheckHierarchy)
    End Function
    <System.Runtime.CompilerServices.Extension> _
    Private Function ClearEntityObject(Of T As Class)(source As T, bCheckHierarchy As Boolean) As T
    If source Is Nothing Then
    Throw New Exception("Null Object cannot be cloned")
    End If
    Dim tObj As Type = source.[GetType]()
    If tObj.GetProperty("EntityKey") IsNot Nothing Then
    tObj.GetProperty("EntityKey").SetValue(source, Nothing, Nothing)
    End If
    If Not bCheckHierarchy Then
    Return CType(source, T)
    End If
    Dim PropertyList As List(Of PropertyInfo) = (From a In source.[GetType]().GetProperties() Where a.PropertyType.Name.Equals("ENTITYCOLLECTION`1", StringComparison.OrdinalIgnoreCase) Select a).ToList()
    For Each prop As PropertyInfo In PropertyList
    Dim keys As IEnumerable = CType(tObj.GetProperty(prop.Name).GetValue(source, Nothing), IEnumerable)
    For Each key As Object In keys
    Dim childProp = (From a In key.[GetType]().GetProperties() Where a.PropertyType.Name.Equals("EntityReference`1", StringComparison.OrdinalIgnoreCase) Select a).SingleOrDefault()
    childProp.GetValue(key, Nothing).ClearEntityObject(False)
    key.ClearEntityObject(True)
    Next
    Next
    Return CType(source, T)
    End Function
    End Module
    But the problem is that when I try to use like this :
    Dim litm, newitm as MyObject
    For Each litm In itemlist
    newitm = litm.Clone()
    newitm.ClearEntityReference(True)
    context.MyObjects.Add(newitm)
    Next
    context.SaveChanges()
    I get an error :
    Public member 'Clone' on type 'MyObject' not found.

  • Get entity as return of collection in entity framework

    how to get entity as return of collection in entity framework,,, i dont have any idea...
    when i select entity and then get column information then no column return .....

    The way the Oracle provider works right now requires that you use a cursor, even if you want to map it to an entity. To map it to an entity, that cursor needs to contain the necessary columns to form the entity (ie: it's returning data from the same table).
    Here's an example from one I have mapped:
    CREATE OR REPLACE PROCEDURE ENVMSTR.P_ORG_UNIT_R_BY_STAFF
    STAFF_ID_P IN NUMBER
    , RESULT_CURSOR_P OUT SYS_REFCURSOR
    ) AS
    BEGIN
    OPEN RESULT_CURSOR_P FOR
    select *
    from dept_organizational_unit d
    where deptorgunit_cd = (select deptorgunit_cd from staff where staff_id = STAFF_ID_P)
    or deptorgunit_cd in ( select deptorgunitrel_parent_cd from dept_org_unit_relation
    start with deptorgunitrel_child_cd = (select deptorgunit_cd from staff where staff_id = STAFF_ID_P)
    connect by prior deptorgunitrel_parent_cd = deptorgunitrel_child_cd);
    END P_ORG_UNIT_R_BY_STAFF;
    web.config:
    <add name="ENVMSTR.P_ORG_UNIT_R_BY_STAFF.RefCursor.RESULT_CURSOR_P" value="implicitRefCursor bindinfo='mode=Output'" />
    With those things set up, I'm able to import the function and map it to the entity that represents the dept_organizational_unit table (that entity is called OrgUnit in the model, but it doesn't really matter what you call it). The interesting thing I found is that in this situation I didn't actually have to add config file entries for each column in the cursor, probably because it maps perfectly to the entity. If I was trying to use a complex type instead then I probably would (and the configuration required to do that gets horrific in a hurry).

  • Calling Oracle stored procedure with out param of user define type from Entity Framework 5 with code first

    Guys i am using Entity Framework 5 code first (I am not using edmx) with Oracle and all works good, Now i am trying to get data from stored procedure which is under package but stored procedure have out param which is user define type, Now my question is
    how i will call stored procedure from entity framework
    Thanks in advance.

    I agree with you, but issue is we have lots of existing store procedure, which we need to call where damn required. I am sure those will be few but still i need to find out.
    If you think you are going to get existing MS Stored Procedures  or Oracle Packages that had nothing to do with the ORM previously to work that are not geared to do simple CRUD operations with the ORM and the database tables, you have a rude awakening
    coming that's for sure. You had better look into using ADO.NET and Oracle Command objects and call those Oracle Packages by those means and use a datareader.
    You could use the EF backdoor, call Oracle Command object and use the Packages,  if that's even possible, just like you can use MS SQL Server Stored Procedures or in-line T-SQL via the EF backdoor.
    That's about your best shot.
    http://blogs.msdn.com/b/alexj/archive/2009/11/07/tip-41-how-to-execute-t-sql-directly-against-the-database.aspx

  • Problem with Top N Query when no rows returned (takes forever)

    I have a table with 100 Million rows and I want to get the latest N records using:
    SELECT * FROM
    (SELECT * FROM tablename WHERE columnA= 'ABC' ORDER BY TIME DESC)
    WHERE rownum <= N;
    This works fine and is very fast when there are rows with columnA= 'ABC' but when there are no rows with columnA= 'ABC' the query takes forever.
    The strange things is that the inner query returns immediately when run on it's own when no rows with columnA= 'ABC' exist e.g.
    SELECT * FROM tablename WHERE columnA= 'ABC' ORDER BY TIME DESC
    So why does it take for ever for to run:
    SELECT * FROM (no rows inner query) WHERE rownum <= N;
    I have also tried using:
    SELECT * FROM
    (SELECT columnA, rank() over(ORDER BY TIME DESC) time_rank
    FROM tablename WHERE columnA='ABC')
    WHERE time_rank <= N;
    which returns instantly when there are now rows but takes much longer than the first query when there are rows.

    I cannot see a real difference:With histogram we can see a difference on the elapse when no row returned and into explain plan.
    SQL> drop table tablename
      2  /
    Table dropped.
    Elapsed: 00:00:00.03
    SQL>
    SQL> create table tablename
      2  as
      3  select sysdate - l time
      4         , decode(trunc(dbms_random.value(1,10)),1,'ABC',2,'DEF',3,'GHI',4,'JKL','MNO') as columnA
      5    from (select level l from dual connect by level <= 1000000)
      6  /
    Table created.
    Elapsed: 00:01:19.08
    SQL>
    SQL> select columnA,count(*) from tablename group by columnA
      2  /
    COL   COUNT(*)
    ABC     110806
    DEF     111557
    GHI     111409
    JKL     111030
    MNO     555198
    Elapsed: 00:00:05.05
    SQL>
    SQL> create index i1 on tablename(time)
      2  /
    Index created.
    Elapsed: 00:00:34.08
    SQL>
    SQL> create index i2 on tablename(columna)
      2  /
    Index created.
    Elapsed: 00:00:30.08
    SQL>
    SQL> exec dbms_stats.gather_table_stats(user,'TABLENAME',cascade=>true)
    PL/SQL procedure successfully completed.
    Elapsed: 00:01:18.09
    SQL>
    SQL> set autotrace on explain
    SQL> SELECT * FROM
      2  (SELECT * FROM tablename WHERE columnA= 'ABC' ORDER BY TIME DESC)
      3  WHERE rownum <= 10
      4  /
    TIME     COL
    17/09/06 ABC
    12/09/06 ABC
    08/09/06 ABC
    07/09/06 ABC
    25/08/06 ABC
    22/08/06 ABC
    13/08/06 ABC
    08/07/06 ABC
    14/06/06 ABC
    01/05/06 ABC
    10 rows selected.
    Elapsed: 00:00:01.04
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=2364 Card=10 Bytes=120)
       1    0   COUNT (STOPKEY)
       2    1     VIEW (Cost=2364 Card=200000 Bytes=2400000)
       3    2       SORT (ORDER BY STOPKEY) (Cost=2364 Card=200000 Bytes=2400000)
       4    3         TABLE ACCESS (FULL) OF 'TABLENAME' (Cost=552 Card=200000 Bytes=2400000)
    SQL>
    SQL> SELECT * FROM
      2  (SELECT * FROM tablename WHERE columnA= 'MNO' ORDER BY TIME DESC)
      3  WHERE rownum <= 10
      4  /
    TIME     COL
    20/09/06 MNO
    19/09/06 MNO
    16/09/06 MNO
    14/09/06 MNO
    13/09/06 MNO
    10/09/06 MNO
    06/09/06 MNO
    05/09/06 MNO
    03/09/06 MNO
    02/09/06 MNO
    10 rows selected.
    Elapsed: 00:00:02.04
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=2364 Card=10 Bytes=120)
       1    0   COUNT (STOPKEY)
       2    1     VIEW (Cost=2364 Card=200000 Bytes=2400000)
       3    2       SORT (ORDER BY STOPKEY) (Cost=2364 Card=200000 Bytes=2400000)
       4    3         TABLE ACCESS (FULL) OF 'TABLENAME' (Cost=552 Card=200000 Bytes=2400000)
    SQL>
    SQL> SELECT * FROM
      2  (SELECT * FROM tablename WHERE columnA= 'PQR' ORDER BY TIME DESC)
      3  WHERE rownum <= 10
      4  /
    no rows selected
    Elapsed: 00:00:01.01
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=2364 Card=10 Bytes=120)
       1    0   COUNT (STOPKEY)
       2    1     VIEW (Cost=2364 Card=200000 Bytes=2400000)
       3    2       SORT (ORDER BY STOPKEY) (Cost=2364 Card=200000 Bytes=2400000)
       4    3         TABLE ACCESS (FULL) OF 'TABLENAME' (Cost=552 Card=200000 Bytes=2400000)
    SQL> set autot off
    SQL>
    SQL> EXECUTE DBMS_STATS.GATHER_TABLE_STATS(user,'TABLENAME',METHOD_OPT => 'FOR COLUMNS SIZE 250 columna')
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:09.08
    SQL>
    SQL> set autotrace on explain
    SQL> SELECT * FROM
      2  (SELECT * FROM tablename WHERE columnA= 'ABC' ORDER BY TIME DESC)
      3  WHERE rownum <= 10
      4  /
    TIME     COL
    17/09/06 ABC
    12/09/06 ABC
    08/09/06 ABC
    07/09/06 ABC
    25/08/06 ABC
    22/08/06 ABC
    13/08/06 ABC
    08/07/06 ABC
    14/06/06 ABC
    01/05/06 ABC
    10 rows selected.
    Elapsed: 00:00:01.03
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=1434 Card=10 Bytes=120)
       1    0   COUNT (STOPKEY)
       2    1     VIEW (Cost=1434 Card=110806 Bytes=1329672)
       3    2       SORT (ORDER BY STOPKEY) (Cost=1434 Card=110806 Bytes=1329672)
       4    3         TABLE ACCESS (FULL) OF 'TABLENAME' (Cost=552 Card=110806 Bytes=1329672)
    SQL>
    SQL> SELECT * FROM
      2  (SELECT * FROM tablename WHERE columnA= 'MNO' ORDER BY TIME DESC)
      3  WHERE rownum <= 10
      4  /
    TIME     COL
    20/09/06 MNO
    19/09/06 MNO
    16/09/06 MNO
    14/09/06 MNO
    13/09/06 MNO
    10/09/06 MNO
    06/09/06 MNO
    05/09/06 MNO
    03/09/06 MNO
    02/09/06 MNO
    10 rows selected.
    Elapsed: 00:00:02.05
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=6219 Card=10 Bytes=120)
       1    0   COUNT (STOPKEY)
       2    1     VIEW (Cost=6219 Card=555198 Bytes=6662376)
       3    2       SORT (ORDER BY STOPKEY) (Cost=6219 Card=555198 Bytes=6662376)
       4    3         TABLE ACCESS (FULL) OF 'TABLENAME' (Cost=552 Card=555198 Bytes=6662376)
    SQL>
    SQL> SELECT * FROM
      2  (SELECT * FROM tablename WHERE columnA= 'STU' ORDER BY TIME DESC)
      3  WHERE rownum <= 10
      4  /
    no rows selected
    Elapsed: 00:00:00.00
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=6 Card=1 Bytes=12)
       1    0   COUNT (STOPKEY)
       2    1     VIEW (Cost=6 Card=1 Bytes=12)
    3 2 SORT (ORDER BY STOPKEY) (Cost=6 Card=1 Bytes=12)
    4 3 TABLE ACCESS (BY INDEX ROWID) OF 'TABLENAME' (Cost=5 Card=1 Bytes=12)
    5 4 INDEX (RANGE SCAN) OF 'I2' (NON-UNIQUE) (Cost=4 Card=1)
    SQL> Nicolas.

  • Exists (SQL query returns at least one row) condition with MAX on 10.2.0.4

    I just wanted to note this on the forum..
    I'm using Apex 3.0.1.00.08
    My DEV environment has just been upgraded from 10g version 10.2.0.2.0 to 10.2.0.4.0.
    I created the following process to select some values into some items on my Form page.
    select  MAX(STAT_YEAR+1)
          , pcd.pct_id
          , pcd.stat_type_id
          , pcd.stat_period_type_id
          , pcd.measurement_id
    into    :P11_STAT_YEAR
          , :P11_PCT_ID
          , :P11_STAT_TYPE_ID
          , :P11_STAT_PERIOD_TYPE_ID
          , :P11_MEASUREMENT_ID
    from  plant_commodity_data pcd
        , stat_type stt
    where pcd.STAT_TYPE_ID = stt.STAT_TYPE_ID
      and pcd.pct_id = :P0_PCT_ID
      and stt.stat_type = 'PRD'
    group by pcd.pct_id
          , pcd.stat_type_id
          , pcd.stat_period_type_id
          , pcd.measurement_id;The process should run conditionally if there was at least one row to select...
    So I copied the SQL into the Process condition, removed the "into" section and set the condition type to be "Exists (SQL query retruns at least one row) ...
    select  MAX(STAT_YEAR+1)
          , pcd.pct_id
          , pcd.stat_type_id
          , pcd.stat_period_type_id
          , pcd.measurement_id
    from  plant_commodity_data pcd
        , stat_type stt
    where pcd.STAT_TYPE_ID = stt.STAT_TYPE_ID
      and pcd.pct_id = :P0_PCT_ID
      and stt.stat_type = 'PRD'
    group by pcd.pct_id
          , pcd.stat_type_id
          , pcd.stat_period_type_id
          , pcd.measurement_id;This worked perfectly until the DEV environment was upgraded from 10g version 10.2.0.2.0 to 10.2.0.4.0.
    The condition would fire even if there were no rows returning.
    I pasted the condition code into SQL Developer connected to the DEV (10.2.0.4.0) environment and it returned no rows.
    To solve the problem, I removed the MAX.
    You can test this using this code if you have access to the two versions... select  MAX(1)
          , sysdate
          , 'Gus'
    from  dual
    where 1 = 2
    group by sysdate, 2Now I know the MAX isn't required in the condition as I'm just trying to find out if any rows exist, but it was there as I copied the code in... I was just wondering why this happened between 10.2.0.2.0 and 10.2.0.4.0?
    Gus..

    Hi Gus,
    try to execute
    select count(*) from dual where exists (select  MAX(1)
          , sysdate
          , 'Gus'
    from  dual
    where 1 = 2
    group by sysdate, 2)in SQL Developer. The above statement is generated by APEX for an "Exists (SQL query retruns at least one row)". Can't test it, because I don't have a 10.2.0.4.0 at hand.
    Does SQL Developer now show the same behavior?
    Patrick
    My APEX Blog: http://www.inside-oracle-apex.com
    The APEX Builder Plugin: http://builderplugin.oracleapex.info/
    The ApexLib Framework: http://apexlib.sourceforge.net/

  • Good or Bad: Repository pattern with Entity framework??

    Suggestions about not to use enttity framework because:
    1) entity framework is itself a Repository pattern
    2) So, what the use of having one more repository pattern over an exisitng repositroy pattern (i.e Entity framework)
    Please suggest.
    Thanks in advance!!

    I've used both nHibernate and the Entity Framework 6 and nHibernate wins hands down as the best orm, despite it's learning curve. ORMs can be massive timesavers as you don't end up writing boiler plate db access code.
    I used 3 different versions on nHibernate over the years. I didn't paticulalry care for any version of nHibernate. I much prefer EF over nHibernate any day of the week, month or year.
    Unlike the previous responder I disagree with testability, each repository should have it's own interface. And if implemented correctly it can save tones of time as you need only mock one or two repository methods rather than 10s or 100s of database
    gateway call using one class per table.
    What? Like a  DAO can't  have an interface, which is just as testable as any repository pattern using an interface when using a test harnerss and testproject to test the DAO? And one has to go beyond some generic repository pattern in
    unit, functional and intergation testing when it comes to data access. 
    Unlike you, I want complete control of the object all aspects of it even in its usage of other DAO(s) that could or would be used, which the  repository pattern doesn't cut it for me. 
    Like I said, I'll take EF over nHibernate, which is much like talking MS SQL Server over Oracle with Oracle being a PITA to work with it.

  • How to use Application Roles with Entity Framework

    How does one call sp_setapprole before a connection used by an Entity Framework object context closes, since the context opens and closes its own connection automatically, as needed? The only relevant event available on a store connection
    (DbConnection ) is StateChange , which does not include a
    ConnectionState of Closing . Attempting to call
    sp_setapprole when ConnectionState is Closed results in, "A severe error occurred on the current command. The results, if any, should be discarded."

    Yes, I realize that I need to call sp_setapprole on an open connection and that I can use
    ExecuteNonQuery or similar mechanisms. What I need to determine is how to do this
    automatically while using the entity framework.
    As I mentioned in my initial inquiry, the EF store connection, which is simply a DbConnection under the covers, does not expose an event (such as Closing) that would allow me to invoke
    sp_setapprole before a connection is closed. The only close event we are given is
    Closed , which is too late to do any good. I'm hoping to avoid burdening our systems with having to manually manage the connection.

Maybe you are looking for