Multiple select statements in PL/SQL

Hi All
I am new to PL/SQL and my experience is in writing TSQL. There we can write a SQL statement like this to return 3 result set
SELECT empname FROM Employee
SELECT authname FROM Author
SELECT athname FROM sport
how can we write the same 3 statements in PL/SQL and attain the 3 resultsets.
I tried to implement the same using PL/SQL anonymous blocks. But it didn't worked.
DECLARE
P_RECORDSET OUT SYS_REFCURSOR
BEGIN
OPEN P_RECORDSET FOR
SELECT empname FROM Employee;
SELECT authname FROM Author;
SELECT athname FROM sport;
END;
can anybody show how it can be done.
Thanks in advance
George
Edited by: user6290570 on Sep 16, 2009 11:23 PM

george2009 wrote:
No i just want to select 3 result sets from 3 select statements, so that it is helpful to compare the resultsets. Compare? How? This is done using the SQL language. Not PL/SQL. Not Java. Not VB. Not anything else.
You would use these other language for flow control and certain forms of conditional logic - but the actual comparison of data sets is done in SQL.
Of course, that is if you do want to do it the most optimal way, that will perform well, and scale well.
SQL is not an I/O API layer - to be used to read() a record and write() a record as if the RDBMS is an ISAM file. That form of row-by-row and slow-by-slow processing dates back to the 80's when we used Cobol.. (or at least for those old farts like me that can actually remember coding in Cobol in the 80's ;-) ).
You want to design and code database applications that are fast, robust, and can scale? Then learn how to use SQL correctly.

Similar Messages

  • Multiple Select statements in EXECUTE SQL TASK in SSIS

    Can we write multiple select statements in execute sql task(SSIS).
    If possible how to assign them to variables in result statement

    Hi ,
    You can use below steps to set result set to variable.
    1.In the Execute SQL Task Editor dialog box, on the General page, select the Single row, Full result set, or XML result set type(According to your result set).
    2.Click Result Set.
    3.To add a result set mapping, click Add.
    4.From the Variables Name list, select a variable or create a new variable.
    What is multiple selection ? May be below can be used in your scenario !
    http://stackoverflow.com/questions/17698908/how-to-set-multiple-ssis-variables-in-sql-task
    What you want to achieve ?
    Thanks
    Please Mark This As Answer or vote for Helpful Post if this helps you to solve your question/problem. http://techequation.com

  • Executing a stored procedure containing multiple Select statements

    Post Author: Beverly
    CA Forum: General
    I am using Crystal  10.0 against a MS SQL 2000 server.
    I am trying to create a report based on a stored procedure that contains multiple select statements.  The sp requires a single parameter (Claim number) and contains 17 Select statements that produce results.
    I am able to use the Add command and execute the sp with the parameter, but I am only getting the results of the first select statement in the sp back in my data set.  Is there a way to have the data from each Select statement returned to my report?
    I have used Crystal for a while, but pretty much for straight-forward reporting.  I am familiar with the basics of SQL.
    I would appreciate any help anyone can offer.
    Thanks.

    Post Author: BISoftware
    CA Forum: General
    I believe Crystal Reports can only handle one recordset at a time, which means it can only handle a single select statement.  The only way I can see around this would be to break up your stored procedure into multiple stored procedures, so that each only contains a single select statement.  Then, use subreports to report on each individual sp. Hope this helps. - Davewww.BusinessSoftwareResource.com

  • How to return the result set of multiple select statements as one result set?

    Hi All,
    I have multiple select statements in my stored procedure that I want to return as one result set 
    for instance 
    select id from tableA
    union 
    select name from table b 
    but union will not work because the result sets datatypes are not identical so how to go about this ?
    Thanks

    You have to CAST or CONVERT (or implicitly convert) the columns to the same datatype.  You must find a datatype that both columns can be converted to without error.  In your example I'm guessing id is an int and name is a varchar or nvarchar. 
    Since you didn't convert the datatypes, SQL will use its data precedence rules and attempt to convert name to an int.  If any row contains a row that has a value in name that cannot be converted to an int, you will get an error.  The solution is
    to force SQL to convert the int to varchar.  So you want something like
    select cast(id as varchar(12)) from tableA
    union
    select name from tableb
    If the datatypes are something other that int or varchar, you must find a compatable datatype and then convert one (or both) of the columns to that datatype.
    Tom

  • Need to create a transaction for multiple select statements?

    Hello,
    I am a newbie and have a question about database transaction, e.g. whether/not to enclose multiple select statements (and select statements only) into a transaction.
    My database is set to transaction isolation level 2: REPEATABLE READ, where dirty read & non-repeatable read are not allowed, only phantom read is allowed.
    Now, in my code I have a number of methods that only contain select statements only. Since they are merely select statements, which don't do any modifications to the data, I am not sure if I am supposed to enclose them into a transaction.
    However, if I don't put them into a transaction will the transaction isolation level takes into effect automatically when another user is modifying the data that I am reading? In other words, I need to make sure the select statements will never do either dirty read or non-repeatable read. But I am not sure if it is necessary to enclose multiple select statements in a transaction, since I believe putting the select statements into a transaction will put some locks to the data being read which may reduce the concurrency of my application.
    Any help/advice would be very much appreciated.
    Duane

    You might want to try asking this on a forum that specific to your database. I suspect the answer can vary depending on the database and probably requires in depth knowledge of what the database does.

  • Select statements inside a SQL Expression field

    Hello
    Why cannot we use the Select statements inside a SQL expression field in Crystal Reports ?
    Any alternatives for this...
    SELECT Top(1) "SomePrivateDatabase"."SPDname" FROM "SomePrivateDatabase"
    inner join "Subscriber" on
    "Subscriber"."SPDID" = "SomePrivateDatabase"."SPDID"
    inner join "UserDetails" on
    "UserDetails"."SPDID" = "SubscriberCore"."SPDID"
    Regards
    Srivatsa
    Edited by: Srivatsa Haridas on Dec 3, 2008 12:17 PM

    Hi Srivatsa,
    SQL Expressions is something the Database supports. We query the Client engine for a list of functions they make available. If the SQL Statement is not list it's not an option and therefore it won't work.
    Your work arounds are to use either a Stored Procedure, this is the most efficient way, all processing is done server side and CR simply waits for the data to format in the report. Another option is to use a
    Command Object, use one CO per report so try to get all data within the SQL statement. We simply pass the SQL to the server and wait for the result set, if you get an error it will be the SQL you typed in. Test in a SQL test tool first to confirm you are getting the data correctly.
    For more assistance in designing reports please post your report deisgn questions to the Reprot Design forums. I am moving this one to that queue.
    Thank you
    Don

  • USING MULTIPLE SELECT VARIABLE IN A SQL STATEMENT

    In HTMLDB, the value of the parameter of a multiple select box is colon delimited(ie P6_Name = Smith:Jones:Burke). Is there an easy way to use this parameter in a SQL statement?
    Example
    Select *
    from names
    where
    Name=P6_Name
    Select *
    from names
    where
    Name IN ('Smith','Jones','Burke')
    Thank you

    Thank you for your response! I'm an idiot. It didn't make sense to me because your talking about a <i>multi-select</i> variable and I was thinking about a <i>select-list</i> variable. My problem is that I need to assign a list of values to one select list item.
    <br>
    For example:
    <br>
    SELECT * FROM EMPLOYEE
    WHERE EMPLOYEE_TYPE IN ( :SELECT_LIST_RETURN_VALUE );
    <br><br>
    With the select list as
    <br><br>
    Display value = All Types, Some Types, One Specific Type<br>
    Return Value = (Type1, type2, type3), (type1, type2), (type3)
    <br><br>
    I've just started in all of this so I'd imagine that I'm probably going about it wrong.

  • Can we give multiple select statements in one function in PL/SQL

    Hi All,
    I am new to the PL/SQL. Can you please help me with the following problem.
    I am cretaing a function in which I have to extract some fields from three tables and to handle three tables I am first extracting the primary key from one table(acting as a foreign key for other table) in a variable declared in declare section, then I am selecting the required fields from the other table by giving that variable name in Where condition. My code is attached as well.
    e.g
    Create or Replace function <function name>(arguments)
    Return return type
    AS
    a1 a%TYPE;
    b_new b%TYPE;
    n fn%TYPE
    Select a into a1 from table1 where b like b_new;
    Select fn into n from table2 where id like a1;
    return a1,n; (can we pass record like this?)
    end;

    Left's first look at the approach you use.. 2 SQL statements that can be done using a single SQL statement.
    Actually it is not as bad as some other code posted here where people go and write complex PL/SQL code to do what could have been done using a single SQL statement.
    There are a couple of golden rules in Oracle development. One of these is to 'Maximise SQL and Minimise PL/SQL'.
    Why take a value from one SQL statement into PL/SQL and then use that value in a second SQL statement?
    Rather do this:
    select
    fn into n
    from table2
    where id like (Select a from table1 where b like b_new);Also keep in mind that in PL/SQL the above SQL construct is only able to fetch a single row - look at the bold above. The variable N can only hold a single value. If that SQL SELECT returns more than one value, how is variable N suppose to hold it?
    I suggest that you read [url http://www.oracle.com/pls/db102/to_toc?pathname=appdev.102%2Fb14261%2Ftoc.htm&remark=portal+%28Books%29]Oracle® Database PL/SQL User's Guide and Reference guide.

  • ORA-00911: invalid character using multiple select statements

    I am getting an ORA-00911: invalid character error when trying to execute 2 select statements using ODP.NET.
    cmd.CommandText = "select sysdate from dual;select sysdate from dual;";
    cmd.Connection = conn;
    cmd.CommandType = System.Data.CommandType.Text;
    conn.Open();
    OracleDataReader dr = cmd.ExecuteReader();
    This works in SQL server but for some reason it appears this does not work in Oracle?
    If this is the case what is a vaiable workaround? Wrapping the 2 statements in a transaction?
    Seems strange that you can't return multiple result sets using in-line sql statements.

    Oracle doesn't support passing multiple statements like that, and this is unrelated to ODP.NET.
    SQL> select * from emp;select * from dept;
    select * from emp;select * from dept
    ERROR at line 1:
    ORA-00911: invalid character
    You could do it via an anonymous block and ref cursors though if you dont want to do it via a stored procedure..
    using System;
    using System.Data;
    using Oracle.DataAccess.Client;
    using Oracle.DataAccess.Types;
    public class test
    public static void Main()
        using (OracleConnection con = new OracleConnection("data source=orcl;user id=scott;password=tiger;"))
            con.Open();
            string strSql = "begin open :refcur1 for select * from emp;" +
                "open :refcur2 for select * from dept;" +
                "open :refcur3 for select * from salgrade;end;";
            using (OracleCommand cmd = new OracleCommand(strSql, con))
                cmd.Parameters.Add("refcur1", OracleDbType.RefCursor, ParameterDirection.Output);
                cmd.Parameters.Add("refcur2", OracleDbType.RefCursor, ParameterDirection.Output);
                cmd.Parameters.Add("refcur3", OracleDbType.RefCursor, ParameterDirection.Output);
                OracleDataAdapter da = new OracleDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                cmd.Parameters["refcur1"].Dispose();
                cmd.Parameters["refcur2"].Dispose();
                cmd.Parameters["refcur3"].Dispose();
                foreach (DataTable dt in ds.Tables)
                    Console.WriteLine("\nProcessing {0} resultset...", dt.ToString());
                    foreach (DataRow row in dt.Rows)
                        Console.WriteLine("column 1: {0}", row[0]);
    }Hope it helps,
    Greg

  • JDBC Sender MSSQL Stored Procedure - Multiple Select Statements

    Hello all,
    I will proceed to tell you my problem, for which solution I request your kind advice:
    Im working in a project for a retailer, which consists in sending the information from erp and sql server to pos thru XI interfaces.
    One of the interfaces is about sending items from sql server to a file so the pos can load it into the system. For doing so I have devloped an stored procedure which function is to return several select statements as many stores the retailer might have, so they can have a different file per store along with its corresponding items in it. 
    The thing is that XI just gets the first select statement and creates the corresponding file, but it seems to ignore the remaining responses as I'm neither getting any file nor an error afterwards.
    So, my question is: is XI capable of handling multiple select responses from an Stored Procedure in graphical mapping??? Or am I just wasting my time trying?
    Thanks in advice for your help.
    Regards.

    Hello Ramkumar,
    After 5 days trying, I finally made it work out applying your advice. Below the short explanation of what I did:
    My Source structure is: Main Node->Row->Records (Material Number, StoreNum, Price, Status)
    My Target structure is: Main Node->File Node->Record Node->Records ( Material Number, Price, Status)
    The key was to make all the occurrences happen against StoreNum node. So, based on what you adviced these two where the key mappings:
    1) The Mapping that will create a new file for each different store that comes in the query (In my case, query was already sort by store using an sql "order by" function, if not you can also use xi node function "sort" as Ramkumar suggested)
    StoreNum->RemoveContext->SplitbyValue (Value Changed)->Collapse Contexts->File Node
    2) The Mapping that will create each record in its corresponding store file:
    StoreNum->RemoveContext->SplitbyValue (Value Changed)->Record Node
    And Voilá !!! It worked.
    Thanks very much Ramkumar.
    Regards.

  • Calculation using multiple select statements - APEX 4.0

    Hello,
    I am new to APEX, PL/SQL and have some SQL knowledge, but I pick up things quickly. I want to make a page item equal to the value of a Select statement minus another Select statement. The statements pull from the same tables and only differ slightly in the where clause. I do not know the best way to create this calculation. Can someone please assist.
    Select Statement #1
    select     sum(JE_TRANSACTIONS.DEBIT_AMOUNT) as "Release"
    from     "REVREC_FORMS" "REVREC_FORMS",
         "JOURNAL_ENTRIES" "JOURNAL_ENTRIES",
         "JE_TRANSACTIONS" "JE_TRANSACTIONS"
    where "JOURNAL_ENTRIES"."RELATED_REVREC"="REVREC_FORMS"."REVREC_ID"
    and     "JOURNAL_ENTRIES"."RECORD_ID_"="JE_TRANSACTIONS"."RELATED_JOURNAL_ENTRY"
    and      "JOURNAL_ENTRIES"."RELEASE_TYPE" ='Release'
    and     "JOURNAL_ENTRIES"."REVENUE_TYPE" ='Software'
    and     "REVREC_FORMS"."REVREC_ID" =:P12_REVREC_ID
    Select Statement #2
    select     sum(JE_TRANSACTIONS.DEBIT_AMOUNT) as "Deferral"
    from     "REVREC_FORMS" "REVREC_FORMS",
         "JOURNAL_ENTRIES" "JOURNAL_ENTRIES",
         "JE_TRANSACTIONS" "JE_TRANSACTIONS"
    where "JOURNAL_ENTRIES"."RELATED_REVREC"="REVREC_FORMS"."REVREC_ID"
    and     "JOURNAL_ENTRIES"."RECORD_ID_"="JE_TRANSACTIONS"."RELATED_JOURNAL_ENTRY"
    and      "JOURNAL_ENTRIES"."RELEASE_TYPE" ='Deferral'
    and     "JOURNAL_ENTRIES"."REVENUE_TYPE" ='Software'
    and     "REVREC_FORMS"."REVREC_ID" =:P12_REVREC_ID

    How about
    select   sum(decode(release_type,'Deferral',je_transactions.debit_amount)) - sum(decode(release_type,'Release',je_transactions.debit_amount)) as result
    from   "REVREC_FORMS" "REVREC_FORMS",
    "JOURNAL_ENTRIES" "JOURNAL_ENTRIES",
    "JE_TRANSACTIONS" "JE_TRANSACTIONS"
    where "JOURNAL_ENTRIES"."RELATED_REVREC"="REVREC_FORMS"."REVREC_ID"
    and  "JOURNAL_ENTRIES"."RECORD_ID_"="JE_TRANSACTIONS"."RELATED_JOURNAL_ENTRY"
    and  "JOURNAL_ENTRIES"."REVENUE_TYPE" ='Software'
    and  "REVREC_FORMS"."REVREC_ID" =:P12_REVREC_IDScott

  • Combine two select statements in one SQL statements

    I have the following two queries that I need to combine into one query, where it updates a single row at the same time.
    SELECT count(*) FROM database.USAGE WHERE SERVICE_TYPE = 'C' AND ACCOUNT = "4837"
    SELECT sum(minutes) FROM database.USAGE WHERE SERVICE_TYPE = 'DA' AND ACCOUNT = "4837"
    I want to insert the values of each select statement into two columns of the same row, as well as insert the account number from the select statement.
    After the query has been executed, the database row will look like this:
    ACCOUNT COUNT SUM
    4837 354 1039202
    I am looking for suggestions on how to:
    - either combine the two into one query
    - simply update each column with the value from each query by updating the row with the account value
    I am a SQL newbie - so I appreciate any assistance.
    Thanks,
    Tony

    Hi, Tony,
    When you're talking about changing the data in tables, "INSERT" means to add a new row, and you'll cause a lot of confusion if you use it to mean something else. So don't say
    "I want to insert the values of each select statement into two columns..."; use some other word, like:
    "I want to put the values of each select statement into two columns ..."
    If you happened to know that those two numbers were 354 and 1039202, you might say:
    UPDATE  table_x
    SET     a_count = 354
    ,       a_sum = 1039202
    WHERE   account = 4837;But you don't know the numbers; you want to have the query figure out what they are.
    In most places where you can use a literal (like 354 or 1039202), you can also use a scalar sub-query, a SELECT statement, enclosed in parentheses, that produces one column and (at most) one row.
    In your case, you can say:
    UPDATE  table_x
    SET     a_count = (SELECT count(*) FROM database.USAGE WHERE SERVICE_TYPE = 'C' AND ACCOUNT = 4837)
    ,       a_sum = (SELECT sum(minutes) FROM database.USAGE WHERE SERVICE_TYPE = 'DA' AND ACCOUNT = 4837
    WHERE   account = 4837;or, to make it more readable:
    UPDATE  table_x
    SET     a_count =
    ( SELECT count (*)
    FROM database.USAGE
    WHERE SERVICE_TYPE = 'C'
    AND ACCOUNT = 4837
    ,       a_sum =
    ( SELECT sum (minutes)
    FROM database.USAGE
    WHERE SERVICE_TYPE = 'DA'
    AND ACCOUNT = 4837
    WHERE   account = 4837;By the way, why are you using double-quotes around 4837? If it's a string, enclose it in single quotes. If it's a number (which I'm assuming in my code), don't enclose it in anything.
    WARNING: scalar sub-queries are somewhat like duct tape: they're extremely useful in certain places, and those places account for about 1% of their use. The other 99% of the time, there's a better way to do things, though the better way may require more expertise.

  • How to JOIN the results of multiple SELECT statements

    Hello,
    I currently have a table where each row represents a single census date for a given tag number, where each tag number can have multiple census dates and data which are represented by their own row in the table.
    I currently have 2 SELECT statements that select all tag numbers given a census date, and would like to combine those 2 queries so that the data is presented in a manner such that for each tag number, instead of obtaining 2 rows for each tag number, I would be presented with 1 row for each tag number consisting of three columns: tag_number, data1, and data2.
    Both of the requested dates are not necessarily present for all tag numbers, and in the event that only one date is present, the other column should contain null, but if both dates are not present for a given tag number, the tag number is omitted.
    The two queries I would like to JOIN are:
    SELECT a.tag_number, a.data AS data1
    FROM tab1 a
    WHERE
    a.census_date='11/21/2009'and
    SELECT b.tag_number, b.data AS data2
    FROM tab2 b
    WHERE
    b.census_date='11/24/2009'The table from which I am selecting the data looks like such:
    tag_number  census_date     data
        1       11/21/2009      10
        1       11/23/2009      11
        1       11/24/2009      12
        2       11/19/2009      13
        2       11/21/2009      14And the data that I would like to result looks like:
    tag_number  data1           data2
        1       10              12
        2       14              nullAny help would be greatly appreciated.
    Thank you in advance,
    -Justin
    Edited by: m8r-qbkka9 on Nov 24, 2009 4:17 PM

    Hi,
    This looks like a job for pivot
    SELECT       a.tag_number
    ,       MAX (CASE  WHEN a.census_date = TO_DATE ('11/21/2009'
                                                       'MM/DD/YYYY'
                   THEN a.data
                END
               )          AS data1
    ,       MAX (CASE  WHEN a.census_date = TO_DATE ('11/24/2009'
                                                       'MM/DD/YYYY'
                   THEN a.data
                END
               )          AS data2
    FROM      tab1    a
    WHERE       a.census_date  IN ( TO_DATE ( '11/21/2009'
                                      , 'MM/DD/YYYY'
                       , TO_DATE ( '11/21/2009'
                                      , 'MM/DD/YYYY'
    GROUP BY  a.tag_number
    ;Comparing DATEs to stirngs, like '11/24/2009', is simply asking for trouble.
    Always use a conversion function (like TO_DATE) or DATE literals instead.

  • Multiple case statements with aggregates- SQL

    Hi guys
    Here is my ddl
    create table TestTable
      Bill_date                    DATE,
      Phone_no                     NUMBER(10),
      Planlvl1                     VARCHAR2(20),
      Planlvl2                     VARCHAR2(20)
      Revenue                      NUMBER                     
    INSERT INTO TestTable
    Values
    ('1/01/2014' , 64221, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014'' , 64221, 'Bundle', 'PlanA', '$32'),
    ('1/01/2014' , 65211, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 65211, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014' , 66211, 'Bundle', 'PlanB', '$34'),
    ('1/01/2014' , 66211, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 66222, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014' , 66222, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 66222, 'Bundle', 'PlanB', '$65'),
    ('1/01/2014' , 32444, 'Non_bundle', 'Casual1', '$32'),
    ('1/01/2014' , 324441, 'Non_bundle', 'Casual2', '$76'),
    ('1/01/2014' , 65444, 'Non_bundle', 'Casual1', '$12'),
    ('1/01/2014' , 65444, 'Bundle', 'PlanB', '$98'),
    ('1/01/2014' , 54322, 'Bundle', 'PlanA', '$12'),
    ('1/01/2014' , 54322, 'Non_bundle', 'Casual', '$12')
    Expected Outcome:
    Bill_date PlanLvl2 PhonenoCount
    '01/01/2014' 'SpecialPack1' 1
    '01/01/2014' 'SpecialPack2' 3
    '01/01/2014' 'Casual1' 1
    '01/01/2014' 'Casual2' 1
    '01/01/2014' 'PlanA' 1
    '01/01/2014' 'PlanB' 1
    Basically I have to count all the phone nos grouped by plans in a certain way:
    If PlanLvl1 = Bundle, then I have to look  at planLvl2 and see if that phone no has ' SpecialPack%' ,and also another plan,them 'Special pack' gets the priority and the phone no gets counted in the special pack.
    In case when PlanLvl1 = Bundle and a phone no has both 'Special Packs' as their plans, then the phone no will be counted under the 'Special Pack' with higher Revenue.
    In case where PalnLvl is 'Bundle' and a phone no has multiple 'Special Packs' and a non special, that ph no will only be counted once under 'Special Pack; of higher rev as compared to the special pack of lower rev.
    Now there are also PlanLvl1 which are 'Non_Bundles' which means they do not have any 'SpecialPacks' but if a ph no with 'NonBundle' plan has 2 different plans under planLvl2, we need to count that ph no for eack planLvl2..
    Then there is a scenario where a ph no can have bundles as well as non bundles and in that case we just have to count that ph no in bundles and not in non-bundles.
    As I mentioned , 'SpecialPack2' will get a preference over special pack 1 if a phone no has got both of these
    Hope this helps

    I;m not sure exactly what your rules are since you specify both "In case when PlanLvl1 = Bundle and a phone no has both 'Special Packs' as their plans, then the phone no will be counted under the 'Special Pack' with higher Revenue" and "As I mentioned ,
    'SpecialPack2' will get a preference over special pack 1 if a phone no has got both of these".  I went with the rule "As I mentioned , 'SpecialPack2' will get a preference over special pack 1 if a phone no has got both of these" since that seemed to match
    the result you say you want.  I also changed the datatypes to valid SQL Server datatypes.
    create table TestTable
    Bill_date DATE,
    Phone_no Decimal(10,0),
    Planlvl1 VARCHAR(20),
    Planlvl2 VARCHAR(20),
    Revenue money
    INSERT INTO TestTable
    Values
    ('1/01/2014' , 64221, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014' , 64221, 'Bundle', 'PlanA', '$32'),
    ('1/01/2014' , 65211, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 65211, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014' , 66211, 'Bundle', 'PlanB', '$34'),
    ('1/01/2014' , 66211, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 66222, 'Bundle', 'SpecialPack1', '$23'),
    ('1/01/2014' , 66222, 'Bundle', 'SpecialPack2', '$3'),
    ('1/01/2014' , 66222, 'Bundle', 'PlanB', '$65'),
    ('1/01/2014' , 32444, 'Non_bundle', 'Casual1', '$32'),
    ('1/01/2014' , 324441, 'Non_bundle', 'Casual2', '$76'),
    ('1/01/2014' , 65444, 'Non_bundle', 'Casual1', '$12'),
    ('1/01/2014' , 65444, 'Bundle', 'PlanB', '$98'),
    ('1/01/2014' , 54322, 'Bundle', 'PlanA', '$12'),
    ('1/01/2014' , 54322, 'Non_bundle', 'Casual', '$12')
    ;With cte As
    (Select Bill_date, Phone_no, Planlvl1, Planlvl2, Revenue,
    Row_Number() Over (Partition By Bill_Date, Phone_no Order By
    Case When Planlvl1 = 'Bundle' And Planlvl2 Like 'SpecialPack2' Then 0 Else 1 End,
    Case When Planlvl1 = 'Bundle' And Planlvl2 Like 'SpecialPack1' Then 0 Else 1 End,
    Case When Planlvl1 = 'Bundle' Then Revenue Else -1 End Desc) As rn,
    Min(Case When Planlvl1 = 'Bundle' Then 0 Else 1 End) Over(Partition By Bill_Date, Phone_no) As NumberHasOnlyNonBundle
    From TestTable)
    Select Bill_date, Planlvl2, COUNT(*) As PhoneNoCount
    From cte
    Where rn = 1 Or NumberHasOnlyNonBundle = 1
    Group By Bill_date, Planlvl2;
    Tom

  • Why does getdate() function return same time value for multiple select statements executed sequentially

    When I run the following code
    set nocount on
    declare @i table(id int identity(1,1) primary key, sDate datetime)
    while((select count(*) from @i)<10000)
    begin
    insert into @i(sDate) select getdate()
    end
    select top 5 sDate, count(id) selectCalls
    from @i
    group by sDate
    order by count(id) desc
    I get the following results. 
    sDate                   selectCalls
    2014-07-30 14:50:27.510 406
    2014-07-30 14:50:27.527 274
    2014-07-30 14:50:27.540 219
    2014-07-30 14:50:27.557 195
    2014-07-30 14:50:27.573 170
    As you can see the select getdate() function returned same time up to the milisecon 406 time for the first date value.  This started happening when we moved our applications to a faster server with four processors.  Is this correct or am I
    going crazy?
    Please let me know
    Bilal

    Observe that adding 2 ms is accurate only with datetime2.  As noted above, datetime does not have ms resolution:
    set nocount on
    declare @d datetime, @i int, @d2 datetime2
    select @d = getdate(), @i = 0, @d2 = sysdatetime()
    while(@i<10)
    begin
    select @d2, @d, current_timestamp, getdate(), sysdatetime()
    select @d = dateadd(ms,2,@d), @i = @i+1, @d2=dateadd(ms,2,@d2)
    end
    2014-08-09 08:36:11.1700395 2014-08-09 08:36:11.170 2014-08-09 08:36:11.170 2014-08-09 08:36:11.170 2014-08-09 08:36:11.1700395
    2014-08-09 08:36:11.1720395 2014-08-09 08:36:11.173 2014-08-09 08:36:11.170 2014-08-09 08:36:11.170 2014-08-09 08:36:11.1700395
    2014-08-09 08:36:11.1740395 2014-08-09 08:36:11.177 2014-08-09 08:36:11.170 2014-08-09 08:36:11.170 2014-08-09 08:36:11.1700395
    2014-08-09 08:36:11.1760395 2014-08-09 08:36:11.180 2014-08-09 08:36:11.170 2014-08-09 08:36:11.170 2014-08-09 08:36:11.1700395
    2014-08-09 08:36:11.1780395 2014-08-09 08:36:11.183 2014-08-09 08:36:11.170 2014-08-09 08:36:11.170 2014-08-09 08:36:11.1700395
    2014-08-09 08:36:11.1800395 2014-08-09 08:36:11.187 2014-08-09 08:36:11.170 2014-08-09 08:36:11.170 2014-08-09 08:36:11.1700395
    DATE/TIME functions:
    http://www.sqlusa.com/bestpractices/datetimeconversion/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

Maybe you are looking for