If statement in sql

regarding the following sql:
SELECT a.lname, a.fname, a.user_id, c.address, c.city,
c.zip, c.addresstypeid, d.descriptor as state
FROM users a, address c, maintstatetype d
WHERE a.user_id = c.user_id(+)
AND c.statetypeid = d.statetypeid(+)
AND c.addresstypeid in (1,2,3,4)
I have a database of users and addresses. Each user can
have multiple addresses and the addresses are
designated by addresstypeid. In plain english, what I want
to pull is "If they have an addresstypeid of 1, pull that one
only, if not, check if they have a 2 and use that, if not, check
for a 3, etc..".
Any help with this?

What you want, then, is to pull the address with the minimum addresstypeid ..
SELECT a.lname, a.fname, a.user_id, c.address, c.city,
c.zip, c.addresstypeid, d.descriptor as state
FROM users a, address c, maintstatetype d
WHERE a.user_id = c.user_id(+)
AND c.statetypeid = d.statetypeid(+)
AND c.addresstypeid =
(select min(c2.addresstypeid)
from address c2
where c2.userid=a.userid
I'm not sure what this will do to your outerjoin, though. You might have to get funky with a union ...
SELECT a.lname, a.fname, a.user_id, c.address, c.city,
c.zip, c.addresstypeid, d.descriptor as state
FROM users a, address c, maintstatetype d
WHERE a.user_id = c.user_id
AND c.statetypeid = d.statetypeid
AND c.addresstypeid =
(select min(c2.addresstypeid)
from address c2
where c2.userid=a.userid
Union all
SELECT a.lname, a.fname, a.user_id, to_char(null), to_char(null),
to_char(null), to_char(null), to_char(null)
FROM users a
WHERE not exists
(select 1
from address c
where c.userid=a.userid
)

Similar Messages

  • If..then..else statement in SQL with 'generalized' conditions in the if sta

    it is possible to write something approaching an if..then..else statement in SQL with 'generalized' conditions in the if statement.
    Attached is the query for the payment register, in which I've written a series of decode statements, one for each possible value of the payment code. The query works OK - however, its specific and as the number of paycodes expand (and they do), the report won't pick up the new paycode until the code is changed. More importantly, the report won't be correct until someone 'discovers' that a paycode is missing, which might take months.
    If I were writing the equivalent of this series of decode statements in Focus, it would be something like this:
    DEFINE.......
    PAYMED/D12.2 = IF PAYMENT_CD LE 18
                   THEN PAYMENT_AMT
                   ELSE 0 ;
    PAYIND/D12.2 = IF PAYMENT_CD GE 19 AND PAYMENT_CD LE 49
                   THEN PAYMENT_AMT
                   ELSE 0 ;
    PAYEXP/D12.2 = IF PAYMENT_CD GE 70
                   THEN PAYMENT_AMT
                   ELSE 0 ;
    PAYREC/D12.2 = IF PAYMENT_CD GE 50 AND PAYMENT_CD LE 69
                   THEN PAYMENT_AMT
                   ELSE 0;
    END
    IN SQL/PLUS:
    SELECT ACCOUNT_NAME,
    LOCATION_1,
    CLMNT_LAST_NAME,
    CLAIM_NBR,
    DATE_OF_INJURY,
    DATE_CHECK_REGISTER,
    PAYEE_NAME_1,
    PAYMENT_CD,
    SERV_OFC,
    CPO_CHECK_NBR,
    PAYMENT_FORM,
    DECODE(PAYMENT_CD, 20, PAYMENT_AMT, 21, PAYMENT_AMT,
    22, PAYMENT_AMT, 23, PAYMENT_AMT, 25, PAYMENT_AMT,
    26, PAYMENT_AMT, 27, PAYMENT_AMT, 28, PAYMENT_AMT,
    29, PAYMENT_AMT, 30, PAYMENT_AMT, 31, PAYMENT_AMT,
    32, PAYMENT_AMT, 33, PAYMENT_AMT, 34, PAYMENT_AMT,
    35, PAYMENT_AMT, 36, PAYMENT_AMT, 37, PAYMENT_AMT,
    39, PAYMENT_AMT, 40, PAYMENT_AMT, 41, PAYMENT_AMT,
    42, PAYMENT_AMT, 43, PAYMENT_AMT, 44, PAYMENT_AMT,
    45, PAYMENT_AMT, 46, PAYMENT_AMT, 47, PAYMENT_AMT,
    48, PAYMENT_AMT, 49, PAYMENT_AMT, NULL) INDEMNITY,
    DECODE(PAYMENT_CD, 0, PAYMENT_AMT, 1, PAYMENT_AMT,
    2, PAYMENT_AMT, 3, PAYMENT_AMT, 4, PAYMENT_AMT,
    5, PAYMENT_AMT, 6, PAYMENT_AMT, 7, PAYMENT_AMT,
    8, PAYMENT_AMT, 9, PAYMENT_AMT, 10, PAYMENT_AMT,
    11, PAYMENT_AMT, 12, PAYMENT_AMT, 13, PAYMENT_AMT,
    14, PAYMENT_AMT, 15, PAYMENT_AMT, 18, PAYMENT_AMT,
    17, PAYMENT_AMT, NULL) MEDICAL,
    DECODE(PAYMENT_CD, 70, PAYMENT_AMT, 71, PAYMENT_AMT,
    72, PAYMENT_AMT, 73, PAYMENT_AMT, 74, PAYMENT_AMT,
    75, PAYMENT_AMT, 76, PAYMENT_AMT, 77, PAYMENT_AMT,
    78, PAYMENT_AMT, 79, PAYMENT_AMT, 80, PAYMENT_AMT,
    81, PAYMENT_AMT, 82, PAYMENT_AMT, 83, PAYMENT_AMT,
    84, PAYMENT_AMT, 85, PAYMENT_AMT, 86, PAYMENT_AMT,
    87, PAYMENT_AMT, 88, PAYMENT_AMT, 89, PAYMENT_AMT,
    90, PAYMENT_AMT, NULL) EXPENSES,
    DECODE(PAYMENT_CD, 50, PAYMENT_AMT, 51, PAYMENT_AMT,
    52, PAYMENT_AMT, 53, PAYMENT_AMT, 54, PAYMENT_AMT,
    55, PAYMENT_AMT, 56, PAYMENT_AMT, 57, PAYMENT_AMT,
    58, PAYMENT_AMT, NULL) RECOVERIES,
    DECODE(PAYMENT_FORM, 'N', PAYMENT_AMT, NULL) NONCASH,
    DATE_FROM_SERVICE,
    DATE_THRU_SERVICE
    FROM &INPUT_TABLES
    WHERE &SECURITYCOND
    DATE_OF_PAYMENT BETWEEN :START_DATE AND :END_DATE
    ORDER BY LOCATION_1, CPO_CHECK_NBR
    As you can see, this is both much easier to write and covers the possibility of expansion of paycodes (expansions always fit in these defined ranges).
    My question is, then, is it possible to write something like this in SQL and, if so, could you give me some sample code? (I'm one of those people who learn best from looking at the code as opposed to a set of instructions)

    Here is one way you could do it.
    Create a table that has columns like:
    Payment_code varchar2(2),
    Effective_Date Date,
    Payment_type varchar2(20),
    Expiration_Date Date)
    Payment type for example could be
    I- indemnity
    M- medical
    R- recovery
    E- expenses
    Let the table name for example be PAYMENT_CODE.
    The select query would look like
    SELECT ACCOUNT_NAME,
    LOCATION_1,
    CLMNT_LAST_NAME,
    CLAIM_NBR,
    DATE_OF_INJURY,
    DATE_CHECK_REGISTER,
    PAYEE_NAME_1,
    PAYMENT_CD,
    SERV_OFC,
    CPO_CHECK_NBR,
    PAYMENT_FORM,
    DECODE(p.payment_type,'E',PAYMENT_AMOUNT,0) expenses,
    DECODE(p.payment_type,'I',PAYMENT_AMOUNT,0) indemnity,
    DECODE(p.payment_type,'M',PAYMENT_AMOUNT,0) Medical,
    DECODE(p.payment_type,'R',PAYMENT_AMOUNT,0) recoveries,
    DECODE(PAYMENT_FORM, 'N', PAYMENT_AMT, NULL) NONCASH
    FROM &INPUT_TABLES,
    PAYMENT_CODE P
    WHERE P.PAYMENT_CODE = SOMEINPUT_TABLE.PAYMENT_CODE
    and other conditions
    The idea is to group all the payment codes into a few groups to reduce the clutter. If there is ever a change to the payment code, you could modify the table and it will be reflected in your select query.

  • Installed hotfix for error 3241 when you run RESTORE FILELISTONLY statement in SQL Server 2008 R2. But still get same errormessage.

    I ran into erro 3241 when you run RESTORE FILELISTONLY statement in SQL Server 2008 R2.
    Found the hotfix 
    Cumulative Update 13 for SQL Server 2008 R2 SP1.
    I have installed this hotfix, now running 10.50.2876.0
    But I still get the same error when trying to restore a backup.
    What else do I need to do?

    second to what bodo said Instead of installing SQL server 2012 SP1 CU13 it would be better to install
    SQL Server 2008 r2 Sp2 SP's are more throughly tested and would include all fixes for CU and Sp1
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
    My Technet Articles

  • Error in statement with sql plus

    Hi,
    I have written this sql statement:
    SELECT  rtrim('Cambio di: '
            || (CASE WHEN nvl(A.DESCRIZIONE_EMITTENTE ,' ') <> nvl(B.DESCRIZIONE_EMITTENTE ,' ') THEN 'Descrizione emittente, ' ELSE '' END)
            || (CASE WHEN nvl(A.INDIRIZZO_SEDE_EMITTENTE,' ') <> nvl(B.INDIRIZZO_SEDE_EMITTENTE,' ') THEN 'Indirizzo sede emittente, ' ELSE '' END)
            || (CASE WHEN nvl(A.SOTTOGRUPPO_ATTIVITA_ECONOMICA,' ') <> nvl(B.SOTTOGRUPPO_ATTIVITA_ECONOMICA,' ') THEN 'Sottogruppo attività economica, ' ELSE '' END)
            || (CASE WHEN nvl(A.RAMO_ATTIVITA_ECONOMICA, ' ') <> nvl(B.RAMO_ATTIVITA_ECONOMICA,' ') THEN 'Ramo attività economica, ' ELSE '' END)
            || (CASE WHEN nvl(A.GRUPPO_EMITTENTE, ' ') <> nvl(B.GRUPPO_EMITTENTE, ' ') THEN 'Gruppo emittente, ' ELSE '' END)
            || (CASE WHEN nvl(A.CAPITALE_SOCIALE_EMITTENTE, 0) <> nvl(B.CAPITALE_SOCIALE_EMITTENTE, 0) THEN 'Capitale sociale emittente, ' ELSE '' END)
            || (CASE WHEN nvl(A.SECTOR, ' ') <> nvl(B.SECTOR, ' ') THEN 'Sector, ' ELSE '' END)
            ,', ') TIPO_VARIAZIONE,
           A.ISICOD ,
           A.EMICOD , 
           A.DESCRIZIONE_EMITTENTE AS DESCRIZIONE_EMITTENTE_T, B.DESCRIZIONE_EMITTENTE AS DESCRIZIONE_EMITTENTE_T1,
           A.INDIRIZZO_SEDE_EMITTENTE AS INDIRIZZO_SEDE_EMITTENTE_T, B.INDIRIZZO_SEDE_EMITTENTE AS INDIRIZZO_SEDE_EMITTENTE_T1,
           A.SOTTOGRUPPO_ATTIVITA_ECONOMICA AS SOTT_ATTIVITA_ECONOMICA_T, B.SOTTOGRUPPO_ATTIVITA_ECONOMICA AS SOTT_ATTIVITA_ECONOMICA_T1,
           A.RAMO_ATTIVITA_ECONOMICA AS RAMO_ATTIVITA_ECONOMICA_T, B.RAMO_ATTIVITA_ECONOMICA AS RAMO_ATTIVITA_ECONOMICA_T1,
           A.GRUPPO_EMITTENTE AS GRUPPO_EMITTENTE_T, B.GRUPPO_EMITTENTE AS GRUPPO_EMITTENTE_T1,
           A.CAPITALE_SOCIALE_EMITTENTE AS CAPITALE_SOCIALE_EMITTENTE_T, B.CAPITALE_SOCIALE_EMITTENTE AS CAPITALE_SOCIALE_EMITTENTE_T1,
           A.SECTOR AS SECTOR_T, B.SECTOR AS SECTOR_T1,
            A.START_DATE AS DATA_AGG_T, B.START_DATE AS DATA_AGG_T1
    FROM SPR_KLERS_IEM A, SPR_KLERS_IEM B
    WHERE A.START_DATE=TRUNC(SYSDATE)
          AND A.ISICOD=B.ISICOD
          AND A.EMICOD=B.EMICOD
          AND B.START_DATE = decode(trim(to_char(sysdate, 'Day')), 'Monday',trunc(sysdate-3), trunc(sysdate-1))
          AND
            nvl(A.DESCRIZIONE_EMITTENTE ,' ') != nvl(B.DESCRIZIONE_EMITTENTE ,' ')
            OR
            nvl(A.INDIRIZZO_SEDE_EMITTENTE,' ') != nvl(B.INDIRIZZO_SEDE_EMITTENTE,' ')
            OR
            nvl(A.SOTTOGRUPPO_ATTIVITA_ECONOMICA,' ') != nvl(B.SOTTOGRUPPO_ATTIVITA_ECONOMICA,' ')
            OR
            nvl(A.RAMO_ATTIVITA_ECONOMICA, ' ') != nvl(B.RAMO_ATTIVITA_ECONOMICA,' ')
            OR
            nvl(A.GRUPPO_EMITTENTE, ' ') != nvl(B.GRUPPO_EMITTENTE, ' ')
            OR
            nvl(A.CAPITALE_SOCIALE_EMITTENTE, 0) != nvl(B.CAPITALE_SOCIALE_EMITTENTE, 0)
            OR
            nvl(A.SECTOR, ' ') != nvl(B.SECTOR, ' ')
            )If I execut it from toad I obtain the correct result but if I execute the statement from sql/plus I obtain these errors:
    SP2-0734: unknown command beginning "nvl(A.DESC..." - rest of line ignored.
    SP2-0042: unknown command "OR" - rest of line ignored.
    SP2-0734: unknown command beginning "nvl(A.INDI..." - rest of line ignored.
    SP2-0042: unknown command "OR" - rest of line ignored.
    SP2-0044: For a list of known commands enter HELP
    and to leave enter EXIT.
    SP2-0734: unknown command beginning "nvl(A.SOTT..." - rest of line ignored.
    SP2-0042: unknown command "OR" - rest of line ignored.
    SP2-0734: unknown command beginning "nvl(A.RAMO..." - rest of line ignored.
    SP2-0042: unknown command "OR" - rest of line ignored.
    SP2-0044: For a list of known commands enter HELP
    and to leave enter EXIT.
    SP2-0734: unknown command beginning "nvl(A.GRUP..." - rest of line ignored.
    SP2-0042: unknown command "OR" - rest of line ignored.
    SP2-0734: unknown command beginning "nvl(A.CAPI..." - rest of line ignored.
    SP2-0042: unknown command "OR" - rest of line ignored.
    SP2-0044: For a list of known commands enter HELP
    and to leave enter EXIT.
    SP2-0734: unknown command beginning "nvl(A.SECT..." - rest of line ignored.
    SP2-0042: unknown command ")" - rest of line ignored.
    ERROR at line 26:
    ORA-00936: missing expression Why this behaviour? The statement is the same and from toad works!
    I do not succed to understand.
    Pleas could someone help me?
    Thanks a lot, bye bye.

    Your are forget = between nvl
    SELECT rtrim('Cambio di: '
    || (CASE WHEN nvl(A.DESCRIZIONE_EMITTENTE ,' ')= nvl(B.DESCRIZIONE_EMITTENTE ,' ') THEN 'Descrizione emittente, ' ELSE '' END)
    || (CASE WHEN nvl(A.INDIRIZZO_SEDE_EMITTENTE,' ') = nvl(B.INDIRIZZO_SEDE_EMITTENTE,' ') THEN 'Indirizzo sede emittente, ' ELSE '' END)
    || (CASE WHEN nvl(A.SOTTOGRUPPO_ATTIVITA_ECONOMICA,' ') = nvl(B.SOTTOGRUPPO_ATTIVITA_ECONOMICA,' ') THEN 'Sottogruppo attivit&agrave; economica, ' ELSE '' END)
    || (CASE WHEN nvl(A.RAMO_ATTIVITA_ECONOMICA, ' ') = nvl(B.RAMO_ATTIVITA_ECONOMICA,' ') THEN 'Ramo attivit&agrave; economica, ' ELSE '' END)
    || (CASE WHEN nvl(A.GRUPPO_EMITTENTE, ' ') = nvl(B.GRUPPO_EMITTENTE, ' ') THEN 'Gruppo emittente, ' ELSE '' END)
    || (CASE WHEN nvl(A.CAPITALE_SOCIALE_EMITTENTE, 0)= nvl(B.CAPITALE_SOCIALE_EMITTENTE, 0) THEN 'Capitale sociale emittente, ' ELSE '' END)
    || (CASE WHEN nvl(A.SECTOR, ' ') = nvl(B.SECTOR, ' ') THEN 'Sector, ' ELSE '' END)
    ,', ') TIPO_VARIAZIONE,
    A.ISICOD ,
    A.EMICOD ,
    A.DESCRIZIONE_EMITTENTE AS DESCRIZIONE_EMITTENTE_T, B.DESCRIZIONE_EMITTENTE AS DESCRIZIONE_EMITTENTE_T1,
    A.INDIRIZZO_SEDE_EMITTENTE AS INDIRIZZO_SEDE_EMITTENTE_T, B.INDIRIZZO_SEDE_EMITTENTE AS INDIRIZZO_SEDE_EMITTENTE_T1,
    A.SOTTOGRUPPO_ATTIVITA_ECONOMICA AS SOTT_ATTIVITA_ECONOMICA_T, B.SOTTOGRUPPO_ATTIVITA_ECONOMICA AS SOTT_ATTIVITA_ECONOMICA_T1,
    A.RAMO_ATTIVITA_ECONOMICA AS RAMO_ATTIVITA_ECONOMICA_T, B.RAMO_ATTIVITA_ECONOMICA AS RAMO_ATTIVITA_ECONOMICA_T1,
    A.GRUPPO_EMITTENTE AS GRUPPO_EMITTENTE_T, B.GRUPPO_EMITTENTE AS GRUPPO_EMITTENTE_T1,
    A.CAPITALE_SOCIALE_EMITTENTE AS CAPITALE_SOCIALE_EMITTENTE_T, B.CAPITALE_SOCIALE_EMITTENTE AS CAPITALE_SOCIALE_EMITTENTE_T1,
    A.SECTOR AS SECTOR_T, B.SECTOR AS SECTOR_T1,
    A.START_DATE AS DATA_AGG_T, B.START_DATE AS DATA_AGG_T1
    FROM SPR_KLERS_IEM A, SPR_KLERS_IEM B
    WHERE A.START_DATE=TRUNC(SYSDATE)
    AND A.ISICOD=B.ISICOD
    AND A.EMICOD=B.EMICOD
    AND B.START_DATE = decode(trim(to_char(sysdate, 'Day')), 'Monday',trunc(sysdate-3), trunc(sysdate-1))
    AND
    nvl(A.DESCRIZIONE_EMITTENTE ,' ') != nvl(B.DESCRIZIONE_EMITTENTE ,' ')
    OR
    nvl(A.INDIRIZZO_SEDE_EMITTENTE,' ') != nvl(B.INDIRIZZO_SEDE_EMITTENTE,' ')
    OR
    nvl(A.SOTTOGRUPPO_ATTIVITA_ECONOMICA,' ') != nvl(B.SOTTOGRUPPO_ATTIVITA_ECONOMICA,' ')
    OR
    nvl(A.RAMO_ATTIVITA_ECONOMICA, ' ') != nvl(B.RAMO_ATTIVITA_ECONOMICA,' ')
    OR
    nvl(A.GRUPPO_EMITTENTE, ' ') != nvl(B.GRUPPO_EMITTENTE, ' ')
    OR
    nvl(A.CAPITALE_SOCIALE_EMITTENTE, 0) != nvl(B.CAPITALE_SOCIALE_EMITTENTE, 0)
    OR
    nvl(A.SECTOR, ' ') != nvl(B.SECTOR, ' ')
    {code}
    Edited by: Salim Chelabi  on 2008-12-09 09:10                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Copying and pasting sql statement in sql*plus

    how do you paste sql statement in sql*plus...I have tried the following options, getting the windows interface for this following the documentation below but that didnt work
    http://download.oracle.com/docs/html/A88829_01/ch3.htm
    then i tried creating a simple .txt file with my sql statement and tried running it using @name(where name is the name of the file) and it is giving me the following error SP2-0310: unable to open file "firstscriot.sql

    Hi,
    Using the command-line interface, copying is a pain. Right click on the title bar at the top of the window, then click on "Edit" and "Mark". After you highlight the text you want to copy, you can press the Enter key to copy it.
    To paste, simply right-click. It doesn't matter how the copy buffer got filled (the cumbersome process I described above, using Control-C in Notepad, or whatever).

  • Usage of Xopen SQL states and SQL Exception?

    Hi
    Is there way to make full use of SQL Exceptions?
    Has anybody used sql states from sql exception?
    It is specified in the API reference that an sql exception object contains an xopen sql state which is a string. But the states in specs are defined as class, subclass.
    The question is how can i make use of these java strings to interpret what exactly happened at the database? Are they really useful? If they are, any utilities which converts these strings to a meaningful message? Any pointers on these question would also help me.
    Thanx in adv.
    Giridhar

    SQLException has inherited a method getMessage() which seems to be quite useful.
    For situations where you want to check on a specific one of several possible (or expected) states (like: maybe the table is not yet created ...), I think you can quite fine use getSQLState() and also getErorCode(). Try out in tests, which information is returned by which constellation, then you can use it for making decisions in your program logic.
    But be aware, that all these informations probably are DBMS specific!

  • Having trouble converting a MS Access IIF statement into SQL Sever 2012

    I am in the process of converting an Access Database to SQL Server 2012.
    The statement that works in MS Access currently right now is
     IIf([$$AMTP46 WITH LAST DRG]![LastOfMSDRG] Is Not Null,[$$AMTP46 WITH LAST DRG]![LastOfMSDRG],[$$AMTP46]![Billing DRG])
    I am not SQL Savvy, can you please help me find a solution to using this IIF statement in SQL. I have tried the CASE statements and no luck there either.
    Thanks

    I presume that you check if LastDRG column is not null then use LastDRG or else use LastOfMSDRG column
    You may also show your case query which didn't work for you.
    Meanwhile try below:
    -- Option 1
    SELECT CASE WHEN [LastOfMSDRG] IS NOT NULL
    THEN [LastOfMSDRG]
    ELSE [Billing DRG]
    END AS 'Output'
    FROM YourTable
    -- Option 2
    SELECT COALESCE([LastOfMSDRG], [Billing DRG])
    FROM YourTable
    -Vaibhav Chaudhari

  • IF statement in SQL*Plus - how to do it

    Hi,
    In SQL*Plus script, I would like to keep conditional checking (IF statement) and proceed. For example, whatever is done in PL/SQL block below, want to do the same in SQL*Plus script, I know partly it can be done using VARIABLE keyword, conditional checking can be done using DECODE in SELECT statement, but I want to carry out a more complex requirement, hence I want to use IF statement somehow in SQL*Plus.
    Another question, how to do spooling in PL/SQL script, it can be done using UTL_FILE, any other option is there to achieve this.
    declare
    v_ind_count int;
    begin
    select count(1) into v_ind_count from user_indexes where index_name = 'index_object_name';
    IF v_ind_count > 0
    THEN
    dbms_output.put_line('index found');
    ELSE
    dbms_output.put_line('index does not exist');
    END IF;
    end;
    /

    Hello,
    SQL*PLUS has no scripting language. It can only execute SQL and PL/SQL scripts. There are some commands like SPOOL or SET but no commands for conditional statements. You should describe your requirements, maybe we can find a way.
    Or you can search the forum, maybe your question has already been answered
    [Google for SQL*PLUS + condition|https://www.google.de/search?q=site%3Aforums.oracle.com+"SQL*PLUS"+condition]
    # {message:id=4189517}
    # {message:id=4105290}
    how to do spooling in PL/SQL scriptFrom within PL/SQL you can use dbms_output, the spool has to be started by the calling SQL script when it is executed in SQL*PLUS. Or you can use utl_file, but then you can only write to a server directory, not into a client file. To give an advice we need more information about what you want to do.
    Regards
    Marcus

  • Can I use if statement in SQL???

    Hello everyone.
    I know that this is a silly question. The answer is no. Instead I should use decode function.
    But what if I dont know all possible outcomes, can I still use decode function?
    Also, I have created a view, in the where clause i want to use if statement. Is it possible to do?
    Thanks in advance,
    Sonya

    here is the view that I created:
    create or replace view import_shipment2
    ( order_no, cust_no,ORDER_SUFFIX,ship_addr1,ship_addr2, city,state,ZIP,country, terms_cd,shipvia_cd,
    freight_cd, shipto_cdoehead,shipto_cdshipto,ship_name,ship_attn,order_status, org_unit_id, order_date,
    estship_dt,confirm_status,gross_inv_value,phone,total_line_no,total_qty_order,total_qty_shipped,
    total_qty_backordered,service,hold_cd,invno)
    as select
    to_char(c.order_no)||'_'||c.ORDER_SUFFIX, c.cust_no,c.ORDER_SUFFIX,d.ship_addr1,
         d.ship_addr2, b.city, b.state, b.zip_code,b.country, d.terms_cd,d.shipvia_cd,d.freight_cd, d.shipto_cd,b.shipto_cd,
         nvl(d.ship_name,b.shipto_attn), nvl2(d.ship_attn,b.shipto_attn,e.contact),d.order_status, d.org_unit_id,
         d.order_date, d.estship_dt, c.confirm_status, f.gross_inv_value ,nvl(d.shipto_recip_phone ,g.phone_no),
         sum(c.line_no),sum(c.qty_order),sum(c.qty_shipped),sum(c.qty_bo),d.shipvia_cd ,d.hold_cd,d.invno
    from shipto_test b, oehead_test d,oedetl_test c, oesummary_test f ,CONTACT_MASTER_TEST e ,CONTACT_PHONE_TEST g
    where c.order_no=d.order_no
    and b.cust_no=d.cust_no
    and b.shipto_cd=d.shipto_cd
    and d.cust_no=f.cust_no
    and d.order_no=f.order_no
    and d.org_unit_id in ('110','120')
         and e.cust_no=d.cust_no
    and e.shipto_cd= d.shipto_cd
    and d.order_status in ('J','S')
    and g.contact_id=e.contact_id
    and g.phone_type='Business'
    Group by
    to_char(c.order_no)||'_'||c.ORDER_SUFFIX, c.cust_no,c.ORDER_SUFFIX,d.ship_addr1,
         d.ship_addr2, b.city, b.state, b.zip_code,b.country, d.terms_cd,d.shipvia_cd,d.freight_cd, d.shipto_cd,b.shipto_cd,
         nvl(d.ship_name,b.shipto_attn), nvl2(d.ship_attn,b.shipto_attn,e.contact),d.order_status, d.org_unit_id,
         d.order_date, d.estship_dt, c.confirm_status, f.gross_inv_value ,nvl(d.shipto_recip_phone ,g.phone_no),
         d.shipvia_cd ,d.hold_cd,d.invno;
    I need to do the validation of the g.phone_type. Does phone number exist at all in table?
    How do I all PL/SQL to this view??
    Thanks once agin,
    Sonya

  • Batch statement with sql server 2000 driver

    Hi,
    I have been using the jdbc bridge and recently upgraded to the sql server 2000 driver. I have some code that was working correctly executing some batch commands. But with the new driver it no longer works. Its throwing errors. Can anyone help? I have tried removing the begin/end statments and that causes a different error to be thrown.
    Statement s = db.createStatement();
    s.addBatch("Begin");
    s.addBatch("use master");
    s.addBatch("EXEC sp_addlogin '" + login +"','" + loginAuth + "','testDB'");
    s.addBatch("use testDB");
    s.addBatch("EXEC sp_grantdbaccess '" + login + "' , '" + login + "'");
    s.addBatch("End");
    s.executeBatch();

    I have been using the jdbc bridge and recently
    upgraded to the sql server 2000 driver. i think you maybe are sol...
    Statement s = db.createStatement();
    s.addBatch("Begin");
    s.addBatch("use master");
    s.addBatch("EXEC sp_addlogin '" +
    p_addlogin '" + login +"','" + loginAuth +
    "','testDB'");
    s.addBatch("use testDB");
    s.addBatch("EXEC sp_grantdbaccess '" +
    ntdbaccess '" + login + "' , '" + login + "'");
    s.addBatch("End");
    s.executeBatch();the documentation from microsoft reads...
    for both CallableStatement and PreparedStatement
    void addBatch (String)
    Not Supported
    Throws "invalid method call" exception.
    is this the error you are seeing?

  • Error creating view with CASE -- WHEN statement in SQL*Plus

    I am using Oracle 8i 8.1.7
    I have an Oracle view which uses CASE...WHEN statements.
    The view compiles fine in DBA studio.
    Using TOAD I saved the view as an *.sql file.
    However, when I try to create the view in SQL*Plus I get the following error:
    SP2-0734: unknown command beginning "CASE WHEN ..." - rest of line ignored.
    According to the documentation CASE -- WHEN has been implemented since since Oracle 8i rel. 2 (8.1.6)

    Well I'm using 8.1.6.3 and CASE and DECODE both work for me:
    SQL> create or replace view v_accs as select account_name, txn,
    2 decode(credit, 0, 'DB', 'CR') t_type
    3 from accs;
    View created.
    SQL> select * from v_accs;
    ACCOUNT_NA TXN T_
    APC 1 DB
    ABC 2 DB
    HJJ 3 DB
    HJH 4 CR
    HJK 5 CR
    APC 6 DB
    APC 7 DB
    ABC 8 DB
    ABC 9 DB
    HJJ 10 DB
    HJJ 11 DB
    HJH 12 DB
    HJH 13 DB
    HJK 14 DB
    HJK 15 CR
    15 rows selected.
    SQL> create or replace view v_accs as select account_name, txn,
    2 case when credit = 0 then 'DB' else 'CR'end as t_type
    3* from accs
    View created.
    SQL> select * from v_accs;
    ACCOUNT_NA TXN T_
    APC 1 DB
    ABC 2 DB
    HJJ 3 DB
    HJH 4 CR
    HJK 5 CR
    APC 6 DB
    APC 7 DB
    ABC 8 DB
    ABC 9 DB
    HJJ 10 DB
    HJJ 11 DB
    HJH 12 DB
    HJH 13 DB
    HJK 14 DB
    HJK 15 CR
    15 rows selected.
    SQL>
    rgds, APC

  • CASE statement in SQL Server

    I am working on a project for ambulance response times. In
    the following query which is in my coldfusion code, I am using a
    CASE statement on a subquery to count the ambulance response times
    in bins. An ambulance should arrive at an emergency incident in
    less than 8:59 (539 seconds) or else it is considered late. In my
    coldfusion Transact-SQL code I am:
    1.) doing a subquery.
    2.) counting the 'event numbers' based on the time it took
    for the ambulance to arrive.
    3.) only counting Lee County ambulances and excluding A6 type
    calls (non-emergencies).
    4.) grouping it by the dateparts.
    SELECT DATENAME("M", I.I_tTimeDispatch) as mths,
    (DATEPART("yyyy", I.I_tTimeDispatch)) AS yr,
    COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
    I.I_tTimeArrival)) BETWEEN 0 AND 539 THEN evnt END) AS OnTime,
    COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
    I.I_tTimeArrival)) BETWEEN 540 AND 1028 THEN evnt END) AS Late,
    COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
    I.I_tTimeArrival)) > 1028 THEN evnt END) AS Outlier
    FROM (SELECT I_EventNumber AS evnt, I_tTimeDispatch,
    I_tTimeArrival, I_kTypeInfo, I_Agency FROM dbo.IIncident) as I
    INNER JOIN dbo.ITypeInfo AS T ON I.I_kTypeInfo =
    T.ITI_TypeInfo_PK
    WHERE I.I_Agency='LC'
    AND T.ITI_TypeID NOT LIKE 'A6*'
    GROUP BY (DATEPART("M", I.I_tTimeDispatch)), (DATENAME("M",
    I.I_tTimeDispatch)), (DATEPART("yyyy", I.I_tTimeDispatch))
    ORDER BY (DATEPART("yyyy", I.I_tTimeDispatch)) ASC,
    (DATEPART("M", I.I_tTimeDispatch)) ASC
    Here is my problem!
    I go into Microsoft Access to verify my statistics and I get
    different counts. For instance, in April 2008 my coldfusion query
    returns 3,944 on-time ambulance responses. My Access query for the
    same time period using only Lee County ambulances and excluding A6
    non-emergencies returns only 3,805 responses. This is an undercount
    of 139 responses. Even for my other time bins I am getting an
    undercount.
    Here is my Access SQL for the on time response bin (<539
    seconds or 8:59):
    SELECT Count(dbo_IIncident.I_EventNumber) AS
    CountOfI_EventNumber
    FROM dbo_IIncident INNER JOIN dbo_ITypeInfo ON
    dbo_IIncident.I_kTypeInfo = dbo_ITypeInfo.ITI_TypeInfo_PK
    WHERE (((dbo_IIncident.I_Agency)="lc") AND
    ((dbo_ITypeInfo.ITI_TypeID) Not Like "a6*") AND
    ((dbo_IIncident.I_tTimeDispatch) Between #4/1/2008# And #5/1/2008#)
    AND
    ((DateDiff("s",[dbo_IIncident]![I_tTimeDispatch],[dbo_IIncident]![I_tTimeArrival]))
    Between 0 And 539));
    How could two queries that are supposed to be doing the same
    thing return such different results?
    To clear up any confusion I am temporarily posting the page.
    Please look at it because it may help you visualize the problem.
    http://lcfcfn01/Secure/GTandLT_8_59.cfm

    Thank you for your quick reply.
    I thought about that, but it isn't what is causing the
    discrepancy in the numbers. This is because Access is hitting the
    SQL Server through ODBC. The time stamps in SQL Server are ODBC
    datetime stamps so they look like this: 4/19/2008 6:20:18 PM
    When my query uses the date #5/1/2008# it is like saying May
    1, 2008 00:00:00. Please correct me if I am wrong. The query won't
    return any results from May 1, 2008 because it stops at zero
    hundred hours. I believe it will only go to April 30, 2008 23:59:59
    and then stop there.
    I do try and play with the date ranges and the 'seconds'
    (<539 or >539) parameter and I consistently get different
    results from what my coldfusion page is telling me.
    David

  • Invalid state in SQL query for a function that was created with no errors.

    SQL> CREATE OR REPLACE FUNCTION overlap(in_start1 IN TIMESTAMP, in_end1 IN TIMESTAMP, in_start2 IN TIMESTAMP, in_end2 IN TIMESTAMP) RETURN NUMBER
    2 IS
    3
    4 BEGIN
    5 IF (in_start1 BETWEEN in_start2 AND in_end2 OR in_end1 BETWEEN in_start2 AND in_end2 OR in_start2 BETWEEN in_start1 AND in_end1) THEN
    6 RETURN 0;
    7 ELSE
    8 RETURN 1;
    9 END IF;
    10 END;
    11 /
    Function created.
    SQL> show errors;
    No errors.
    SQL>
    SQL> SELECT * FROM tbl where overlaps(current_time,current_time+1,current_time-1,current_time+2) = 0;
    SELECT * FROM tbl where overlaps(current_time,current_time+1,current_time-1,current_time+2) = 0
    ERROR at line 1:
    ORA-06575: Package or function OVERLAPS is in an invalid state
    I do not understand why overlaps is returned as in invalid state in the query, when it was created with no errors earlier. Could anyone help me?

    Marius
    Looking at the logic you are trying to create it looks like you are looking for overlapping time periods.
    Consider two date/time ranges:
    Range 1 : T1 - T2
    Range 2 : T3 - T4
    Do they overlap?
    1) No: T1 < T4 (TRUE)  T2 > T3 (FALSE)
    T1 --- T2
               T3 --- T4
    2) Yes: T1 < T4 (TRUE)  T2 > T3 (TRUE)
    T1 ---------- T2
               T3 --- T4
    3) Yes: T1 < T4 (TRUE)  T2 > T3 (TRUE)
    T1 -------------------- T2
               T3 --- T4
    4) Yes: T1 < T4 (TRUE)  T2 > T3 (TRUE)
                   T1 ----- T2
               T3 --- T4
    5) Yes: T1 < T4 (TRUE)  T2 > T3 (TRUE)
               T1 --- T2
           T3 ------------ T4
    5) No: T1 < T4 (FALSE) T2 > T3 (TRUE)
                    T1 --- T2
           T3 --- T4Answer: Yes they overlap if:
    T1 < T4 AND T2 > T3
    So you can code the logic in your SQL as simply:
    SELECT *
    FROM tbl
    WHERE range1_start < range2_end
    AND    range_1_end > range2_startIf you go around implementing PL/SQL functions for simple logic that can be achieved in SQL alone then you cause context switching between the SQL and PL/SQL engines which degrades performance. Wherever possible stick to just SQL and only use PL/SQL if absolutely necessary.

  • Xi JDBC Adapter - Query SQL Statement & Update SQL Statement

    Hi!
    I configure the JDBC adapter sender (XI) to take data from Oracle database.
    I set the Query and Update SQL Statement in the Processing parameters of the communication channel in this way:
    Query SQL Statement :
    SELECT * FROM XI_TABLE WHERE STATUS = 'WAIT' ORDER BY ROW_NUM
    Update SQL Statement :
    UPDATE XI_TABLE SET STATUS = 'DONE', DATE = SYSDATE WHERE STATUS = 'WAIT'
    My question is :
    If a new record with the field STATUS = 'WAIT' is added to the table (xi_table) during the time between the execution of the query statement and the start of the update statement, what will happen to that record during the update?
    There is a way to avoid the update of that record? or to pass to the update statement only the record selected in the query statement?
    Please, may you give me some example?
    Thanks,
    Francesco

    hi,
    did you check "Isolation Level for Transaction"
    for the sender jdbc adapter?
    http://help.sap.com/saphelp_nw04/helpdata/en/7e/5df96381ec72468a00815dd80f8b63/content.htm
    Regards,
    michal

  • How to use Conditional statements in SQL Loader control file

    Hi,
    I am using sql loader to load a flat file to the table. I am using control file for this purpose as show below:
    LOAD
    INTO TABLE store_shrink
    TRUNCATE
    FIELDS TERMINATED BY "     "
    TRAILING NULLCOLS
    SITE_ID char,
    ST_SHRINK char,
    ST_REVENUE char,
    SHRINK_PR char ":ST_SHRINK/:ST_REVENUE"
    My question is this. If in the flat file the value of 'ST_REVENUE' is '0', then I want 'SHRINK_PR' to be '0' as well, and skip the calculation (:st_shrink/:st_revenue).
    How to achieve this with the conditional statement or using any Oracle function?
    Any help or suggestion is greatly appreciated.
    Thanks in advance.

    Hi there,
    I tried the following in my above query and it doesn't work somehow. Anyone has an idea? I have been on internet throughout but to no avail. Please help:
    LOAD
    INTO TABLE store_shrink
    TRUNCATE
    FIELDS TERMINATED BY "     "
    TRAILING NULLCOLS
    SITE_ID char,
    ST_SHRINK char,
    ST_REVENUE char,
    SHRINK_PR char "case (when :st_revenue<>'0.00' then :SHRINK_PR=:ST_SHRINK/:ST_REVENUE else :SHRINK_PR='0.00') end"
    )

Maybe you are looking for

  • Foreign Exchange entry not posted

    Hi I posted a vendor invoice $100 @ Rs. 50 on 28th September for Vendor A. Payment term is defined in Vendor master. Now i posted vendor payment for the same invoice $100@ Rs.53. Now SAP is not passing payment entry at Rs. 5300 (53 x 100). Its passin

  • Abstract method in constructor

    Hi! This is simplification of my 'problem'. I solved it by more clear approach but I still don't understand the result. Output is: true, false, true. I would expect true, true, true. I use Mac Java 1.4.1. public class TestAbstract { public static voi

  • NotSerializableException

    I have a class that imports : import com.sun.xml.tree.ElementNode.*; in this class i use createElement function, getElementsByTagName it gives an exception as : java.io.NotSerializableException: com.sun.xml.tree.ElementNode The console output is: jav

  • A row delimiter should be seen after column number

    A column delimiter was seen after column number <70> for row number <533394> in file The total number of columns defined is <70>, so                                                       a row delimiter should be seen after column number <70>. Please

  • Sony says 2011 Xperia phones might get Android 4.1 Jelly Bean

    Hi! looks like not all is lost! http://www.theinquirer.net/inquirer/news/2195619/sony-says-2011-xperia-phones-might-get-android-41-j...