PL/SQL Function to convert fields & set max length

I am having a problem with the following assignment:
Write a stored PL-SQL function called namefct that will convert two varchar2 fields (first and last names) into the format: lastname, firstname with a maximum length of 10 chars. If the combined size of the two names is greater than 10 characters, you will issue an error message indicating the name has been shortened to 10 characters and return only the first ten characters, otherwise return the entire name. Test the namefct function by using the staff table created in Part 1 (above). Turn in: the SQL statements to build the function, execute the sample code and the resulting output.
This is the start of my attempt, excluding the error message that is to be issued:
CREATE OR REPLACE FUNCTION namefct (fname VARCHAR2, lname VARCHAR2) IS
BEGIN
column "full name" format a10;
SELECT namefct(fname, lname) as "full name" from staff;
END namefct
Any advice or assistance would be greatly appreciated, since my Professor seems unwilling to assist me. Thanks!

Write a stored PL-SQL function called namefct that
will convert two varchar2 fields (first and last
names) into the format: lastname, firstname with a
maximum length of 10 chars. If the combined size of
the two names is greater than 10 characters, you will
issue an error message indicating the name has been
shortened to 10 characters and return only the first
ten characters, otherwise return the entire name.
Test the namefct function by using the staff table
created in Part 1 (above). Turn in: the SQL
statements to build the function, execute the sample
code and the resulting output.Firstly you need to consider what you have already been taught as you need to ensure that you code your function according to the purpose of the assignment. i.e. are you supposed to be demonstrating the use of returning values in a function or are you supposed to be demonstrating the use of exception handling etc.
The main tricky bit with this assignment is the requirement to show an error message and still return a value. If you were to just raise an exception with the error message (e.g. raise application error) then you won't be able to actually return a value. Because it's a function and not a procedure that has been specified you aren't returning the value in an OUT parameter which would have made passing the value back and raising an exception easier.
So, the only real way to have a function and allow it to show an error message would be something like...
SQL> ed
Wrote file afiedt.buf
  1  CREATE OR REPLACE FUNCTION f_name(p_forename IN VARCHAR2, p_surname IN VARCHAR2) RETURN VARCHAR2 IS
  2    name_too_long EXCEPTION;
  3  BEGIN
  4    IF LENGTH(p_surname||', '||p_forename) > 10 THEN
  5      RAISE name_too_long;
  6    END IF;
  7    RETURN p_surname||', '||p_forename;
  8  EXCEPTION
  9    WHEN name_too_long THEN
10      DBMS_OUTPUT.PUT_LINE('Name Too Long. Truncating to 10 chrs.');
11      RETURN SUBSTR(p_surname||', '||p_forename, 1, 10);
12* END;
SQL> /
Function created.
SQL> select f_name('FRED','SIMS') from dual;
F_NAME('FRED','SIMS')
SIMS, FRED
SQL> select f_name('FRED','SIMKINSON') from dual;
F_NAME('FRED','SIMKINSON')
SIMKINSON,
Name Too Long. Truncating to 10 chrs.
SQL>Note: Tutors/Professors are very wise to checking your work on the internet to make sure it hasn't been copied, so I would suggest you don't just copy this verbatim, but actually read it and understand how it's working and write your own version, taking account of what you have been taught so far and not using things you haven't been taught.
;)

Similar Messages

  • Setting max length of the field when using Context Model Node

    I have created a model using Import Adaptive Web Service model option (a web service was a wrapper around SAP BAPI function module).
    There were no dictionary types created in the Local dictionary as a result of import.
    I have mapped the context of the controller to the model node.
    One of the fields in the model is name     CUSTOMER_NUMBER type string;
    Corresponding element in the wsdl of the web service is
    <xsd:element name="CUSTOMER_NUMBER" type="tns:char10" />
    I have created a view with the input filed mapped to the CUSTOMER_NUMBER field of the model node.
    When I type more than 10 chars into the field and hit the search button, I get a com.sap.dictionary.runtime.Ddcheck exception that the length of the field should be less than 10 chars.
    How can I set the max length of the field in design time to prevent runtime exception?
    Thanks,
    Julia

    Thank you for your reply.
    Java trim function will trim the white spaces only, not the characters.
    I can code check length functionality before calling execute function (the function that call the web service).
    I can also create a dictionary structure based on the model structure; create a context value node based on the dictionary structure and use WDCopyService API to move the data between value node and model node.
    I was looking for the best practice...
    When importing model based on Adaptive RFC, the dictionary structures are imported together with the model. This does not happen for Adaptive web service - hence there is a need to add coding for simple checks.
    Julia

  • How to set max length for TextField ?

    how do i go about setting a max length for a TextField in jdk1.1.8 ?
    a while back there was a topic on this but it was for jdk1.0
    please help

    well if it works in 1.0 it will most likely also work in 1.1.8 if it is depricated you can use the -deprication option during compilation to see what is derpricated and what method i advised to use now.
    there may however be an easyer way in 1.1.8 but i don't know that.
    hope this helps you,
    Robert

  • Set max length for input parameter in SSRS

    I have an input parameter (@year)   to display a simple report. This input parameter taken Year from user (ex: 2015) manually. Here my problem is to restrict the user to max length of
    4. It should allow only (ex:2015) not (ex:20155) like that. Can any one please suggest me how to do this. 

    Hi SaikumarN,
    According to your description, you want to restrict the length of values which user type in the parameter box.
    In Reporting Services, it’s not supported to limit the length of the typed value in the parameter box currently. For your requirement, you could provide Microsoft a feature request at
    https://connect.microsoft.com/SQLServer, so that we can try to modify and expand the product features based on your needs.
    If you have any question, please feel free to ask.
    Best regards,
    Qiuyun Yu
    Qiuyun Yu
    TechNet Community Support

  • Does it has some method to set Max Length on Field!

    I want to set a maximun length on textfield and jtable cell to control the number of character on the field.
    do you have any way?
    thanks!

    aaaaalmost, quizmaster.
    But your code doesnt check the result size.
    If offs = 100 and maxlength = 100, it would
    allow any String to be inserted.
    Anyway...is a detail of course.
    one other possibility, also improveable:
    public class CharacterLimitedDocument extends PlainDocument
      private int maxNumberOfCharacters = 64;
      public CharacterLimitedDocument(int maxCharacters )
        super();
        this.maxNumberOfCharacters = maxCharacters;
      public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
        if( this.getLength() + str.length()  < maxNumberOfCharacters )
           super.insertString(offs,str,a);
    } // CharacterLimitedDocument

  • How to set max length to textfield?

    I have a textfield. I want to set maxlength to this textfield. Example, length = 3.
    Help me?

    I succeeded. That link you sent very well. Thanks you. Then it's code:
    JTextFieldLimit.java
    import javax.swing.text.*;
    //import com.sun.java.swing.*;
    //import javax.swing.text.*;
    public class JTextFieldLimit extends PlainDocument {
       private int limit;
       // optional uppercase conversion
       private boolean toUppercase = false;
       JTextFieldLimit(int limit)
        super();
        this.limit = limit;
       JTextFieldLimit(int limit, boolean upper) {
        super();
        this.limit = limit;
        toUppercase = upper;
       public void insertString
         (int offset, String  str, AttributeSet attr)
           throws BadLocationException {
        if (str == null) return;
        if ((getLength() + str.length()) <= limit) {
          if (toUppercase) str = str.toUpperCase();
          super.insertString(offset, str, attr);
    tswing.java
    import java.awt.*;
    import javax.swing.*;
      //import javax.swing.*;
      public class tswing extends JApplet{
        JTextField textfield1;
        JLabel label1;
        public void init() {
          getContentPane().setLayout(new FlowLayout());
          label1 = new JLabel("max 10 chars");
          textfield1 = new JTextField(15);
          getContentPane().add(label1);
          getContentPane().add(textfield1);
          textfield1.setDocument
             (new JTextFieldLimit(10));
    TextField.html
    <html>
    <applet code=tswing width=500 height=500>
    </applet>
    </html>
    By tungld_c0701m+

  • Using sql functions (min, max, avg) on varray or table collection

    Hi,
    I would like to know if there is a way to use sql function or oracle sql function like Min,Max, Avg or percentile_cont on varray or table collection ?
    Does anyone encountered this type of problem ?
    Thanks

    Yes you can apply Min,Max, Avg... if varray or table collection type is SQL (created in the databaase) UDF, not PL/SQL declared type:
    SQL> set serveroutput on
    SQL> declare
      2      type str_tbl_type is table of varchar2(4000);
      3      str_tbl str_tbl_type := str_tbl_type('X','A','D','ZZZ');
      4      max_val varchar2(4000);
      5  begin
      6      select max(column_value)
      7        into max_val
      8        from table(str_tbl);
      9      dbms_output.put_line('Max value is "' || max_val || '"');
    10  end;
    11  /
          from table(str_tbl);
    ERROR at line 8:
    ORA-06550: line 8, column 18:
    PLS-00642: local collection types not allowed in SQL statements
    ORA-06550: line 8, column 12:
    PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    ORA-06550: line 6, column 5:
    PL/SQL: SQL Statement ignored
    SQL> create or replace type str_tbl_type is table of varchar2(4000);
      2  /
    Type created.
    SQL> declare
      2      str_tbl str_tbl_type := str_tbl_type('X','A','D','ZZZ');
      3      max_val varchar2(4000);
      4  begin
      5      select max(column_value)
      6        into max_val
      7        from table(str_tbl);
      8      dbms_output.put_line('Max value is "' || max_val || '"');
      9  end;
    10  /
    Max value is "ZZZ"
    PL/SQL procedure successfully completed.
    SQL> SY.

  • Totals of calculated field w/ PL/SQL function

    I have a worksheet with a numeric field that is calculated using
    a registered PL/SQL function. When I add totals to the sheet, no
    total appears for this column. Is this a known issue, or is
    there something else going on?
    Thanks,
    Charles

    I have the same problem. I used to work with Discoverer 4 and all the totals were there, but after the upgrade to 9.0.4 the totals for the calculated items that are based on stored procedures are gone. It has something to do with the procedures because the calculated items that do not call procedures do have the totals.
    What is meant by the default setting of "Data point"? I cannot find anything like it in the administrator.....

  • Set label of an item dynamically through pl/sql function

    Hi ,
    How Can I get the label of an item dynamically through a pl/sql function.
    I have a table that stores the label name for these items.
    I want to set the label for the item based on the value in my table ?
    Is it possible ?
    any ideas ?
    Thanks in advance,
    Dippy
    Edited by: Dippy on Feb 23, 2010 11:02 AM
    Edited by: Dippy on Feb 23, 2010 11:02 AM

    If I understand you correctly, you are using a standard report region, but want to dynamically name the column headers? The only way I've been able to get this to work is to create hidden items for each column header, calculate the value you want for each item, then reference the item in the column header using &item_X. for the column header name.
    The problem is that at this point, APEX doesn't allow for dynamic column naming unless you want to do everything yourself using a PL/SQL process that builds the report table manually. I've done that for certain complex reporting tools.
    I understand it's tedious to create all the column header items; I have one report that has over 72 items used in this way. It was a pain, but it got the job done.

  • Returning a set of registers in a PL/SQL function

    Does anybody knows if there is some way to return a set of registers (like a cursor) in a PL/SQL function without using a temporary table?
    Thank you

    To: [email protected]
    Sub: Returning a set of registers in a PL/SQL function
    Hi: Nei S
    Create a Package first:
    CREATE OR REPLACE PACKAGE sp_xxxPKG AS
    TYPE RT1 IS RECORD (
    sp_col1 emp.emp_no%TYPE,
    sp_col2 emp.emp_name%TYPE);
    TYPE RCT1 IS REF CURSOR RETURN RT1;
    END;
    Then Create a Procedure:
    CREATE OR REPLACE PROCEDURE sp_xxx (
    RC1 IN OUT sp_xxxPKG.RCT1) AS
    BEGIN
    OPEN RC1 FOR
    SELECT emp_no, emp_name FROM emp;
    RETURN;
    END;
    null

  • PL/SQL Function source of text field

    I have the following code as a PL/SQL function body as the source of a text item. There is a group_options table that specifies if the user group selected has fixed pricing or
    can key in a price. For the fixed price groups, I was wanting to have the text field auto-populate and for the nonfixed price groups, I just wanted an empty text field for them to key in the price. The check boxes on the page for purchasing an item or leasing an item determine which table the pricing comes from. I don't get an error message, but there is something APEX doesn't like about the code below because I get the 'page cannot be found' message. Do you see a problem with the code below? Last week, it would not work and then mysteriously started to work. Today, it started out not working, so there has to be something flakey about it.
    Thank you in advance.
    Kelly
    DECLARE
    vfixed NUMBER;
    vpurprice NUMBER;
    vleasprice NUMBER;
    BEGIN
    SELECT FIXED_PRICE INTO vfixed FROM UPSL_DEV.GROUP_OPTIONS WHERE USER_GROUP =
    :P7_GROUP ;
    IF vfixed = 1 and :P9_PURCHASE = 1 THEN
    SELECT PURCHASE_PRICE INTO vpurprice FROM UPSL_DEV.PRICE_GRID g WHERE g.user_GROUP = :P7_GROUP and g.equip_code =:P9_ITEMCODE ;
    return vpurprice;
    ELSIF vfixed = 0 and :P9_PURCHASE = 1 THEN
    return NULL;
    END if;
    IF vfixed = 1 and :P9_LEASE = 1 THEN
    SELECT MIN into vleasprice from UPSL_DEV.PRICE_GRID_LEASE l WHERE l.equip_code = :P9_ITEMCODE AND l.user_group = :P7_GROUP and l.term = :P9_LEASETERM;
    RETURN vleasprice;
    ELSIF vfixed = 0 and :P9_LEASE = 1 then
    RETURN NULL;
    END if;
    END;

    Put a "return null;" statement at the end of the block to allow for your logic not covering all cases. It may presently be getting a "function returned without value" error that is inconveniently suppressed in the page output.
    Just a guess.
    Scott

  • Setting Oracle Permissions for file access from a pl/sql function

    I have a pl/sql function that calls a java method which moves a
    file from a directory to another.
    Since we are using Linux, Oracle wants some permissions.
    Those permissions are set using:
    call dbms_java.grant_permission(USER, 'java.io.FilePermission',
    FILE, permission)
    OK, i want to use this in my pl/sql function, but it doesn't
    work.
    My function looks like something like this:
    -- some pl/sql code
    dbms_java.grant_permission(someUSER, 'java.io.FilePermission',
    sourceFILE, 'write');
    dbms_java.grant_permission(someUSER, 'java.io.FilePermission',
    destFILE, 'write');
    flag := move(sourceFILE, destFILE);
    -- flag is for 1 -> done and 0 -> error
    -- some more code ...
    The problem is the lines of
    dbms_java.grant_permission(someUSER, 'java.io.FilePermission',
    sourceFILE, 'write');
    do not work!
    When i grant permissions manually in sql plus it works great,
    but when i do it from the function it does not work!
    Any ideas anyone?
    Any help would be appreciated.

    The command :
    dbms_java.grant_permission
    (someUSER, 'java.io.FilePermission',sourceFILE, 'write');
    is right.
    Open sqlplus
    Connect as sys or system
    type :
    execute dbms_java.grant_permission
    (someUSER, 'java.io.FilePermission',sourceFILE, 'write');
    commit;
    try to compile again your procedure...does it work now ?
    bye
    Giovanni Regola

  • Convert Access Module to SQL Function - Hex To Dec conversion

    I need to convert an Access Module to a SQL Function but not sure how to successfully accomplish this.
    The module has several different functions to convert hexadecimal numbers to decimal and vice versa. I am not sure if I needed to break out each module function into a seperate function in SQL or not. Any help would be appreciated.
    Here is the actual module that needs to be converted:
    Public Function MEID_DecToHex(mMEIDDec As String) As String
        'Dim mMEIDDec As String
        Dim mManNum As Double
        Dim mSerialNum As Double
        Dim mMEIDHex As String
        Dim mManHex As String
        Dim mSerialHex As String
        'mMEIDDec = "268435457304109828"
        '*** Check MEID digits, make sure it is 18 digits else return invalid
        If Len(mMEIDDec) = 18 Then
            '*** 18 digit decimal code: 1st 10 digits is for the Manufacturer and last 8 digits is for the Serial Number
            mManNum = Left(mMEIDDec, 10)
            mSerialNum = Right(mMEIDDec, 8)
            '*** Convert MEID Dec to Hex
            mManHex = DecToHex(mManNum)
            mManHex = fntPad(mManHex, "0", 8)
            mSerialHex = DecToHex(mSerialNum)
            mSerialHex = fntPad(mSerialHex, "0", 6)
            MEID_DecToHex = mManHex & mSerialHex
        ElseIf Len(mMEIDDec) = 11 Then
            '*** 11 digit decimal code: 1st 3 digits is for the Manufacturer and last 8 digits is for the Serial Number
            mManNum = Left(mMEIDDec, 3)
            mSerialNum = Right(mMEIDDec, 8)
            '*** Convert MEID Dec to Hex
            mManHex = DecToHex(mManNum)
            mManHex = fntPad(mManHex, "0", 2)
            mSerialHex = DecToHex(mSerialNum)
            mSerialHex = fntPad(mSerialHex, "0", 6)
            MEID_DecToHex = mManHex & mSerialHex
        Else
            MEID_DecToHex = "Invalid"
        End If
    End Function
    Public Function MEID_HexToDec(mMEIDHex As String) As String
        'Dim mMEIDDec As String
        Dim mManNum As String
        Dim mSerialNum As String
        'Dim mMEIDHex As String
        Dim mManDec As String
        Dim mSerialDec As String
        'mMEIDHex = "a000001937b27a"
        ' Remove any spaces befor or after the string
        mMEIDHex = Trim(mMEIDHex)
        '*** Check MEID digits, make sure it is 14 digits else return invalid
        If Len(mMEIDHex) = 14 Then
            '*** 14 hexadecimal digits: 1st 8 digits is for the Manufacturer and last 6 digits is for the Serial Number
            mManNum = Left(mMEIDHex, 8)
            mSerialNum = Right(mMEIDHex, 6)
            '*** Convert MEID Hex to Dec
            mManDec = HexToDec(mManNum)
            mManDec = fntPad(mManDec, "0", 10)
            mSerialDec = HexToDec(mSerialNum)
            mSerialDec = fntPad(mSerialDec, "0", 8)
            MEID_HexToDec = mManDec & mSerialDec
        ElseIf Len(mMEIDHex) = 8 Then
            '*** 8 digit Hex code: 1st 2 digits is for the Manufacturer and last 6 digits is for the Serial Number
            mManNum = Left(mMEIDHex, 2)
            mSerialNum = Right(mMEIDHex, 6)
            '*** Convert MEID Dec to Hex
            mManDec = HexToDec(mManNum)
            mManDec = fntPad(mManDec, "0", 3)
            mSerialDec = HexToDec(mSerialNum)
            mSerialDec = fntPad(mSerialDec, "0", 8)
            MEID_HexToDec = mManDec & mSerialDec
        Else
            MEID_HexToDec = "Invalid"
        End If
    End Function

    Try link
    you can create & use CLR function
    or you can simply convert on fly refer below link
    http://blog.sqlauthority.com/2010/02/01/sql-server-question-how-to-convert-hex-to-decimal/
    http://blog.sqlauthority.com/2012/07/26/sql-server-answer-how-to-convert-hex-to-decimal-or-int/
    decimal to hex
    http://stackoverflow.com/questions/13643729/decimal-to-hex-conversion-in-sql-server-2008

  • How to set max size for a custom field ucm11g

    Hi,
    I need to set maximum length to a custom field created in ucm11g 11.1.1.6
    The field's data type is Text and for example i want to limit the length to 10 characters
    Any example how to do this ??
    Regards
    Carlos

    Hi ,
    If you are looking to limit the number of characters that can be entered to the field from GUI then a global side effect and rule combination will help you achieve it . It would be something like this :
    This is done by leveraging Side Effects under Rules - Rules Activation Conditions. You also need to set the Rule as Global for this to be effective across the system.
    In there the following has to be set:
    <$dDocTitle:maxLength=80$>
    <$dDocName:maxLength =50$>
    Set the above side effect in the rules and corresponding Profile need to refer it for being able to limit the number of characters that can be entered for Title and Content ID.
    Custom metadata too can be controlled in the same way . For example, if metadata "Version" need to limit the number of characters being entered then "Side Effects" to be set is as follows :
    <$xVersion:maxLength=50$>
    NB - the maxLength parameter is not supported for fields of type Memo. It will only take effect on standard text fields.
    Thanks,
    Srinath

  • How display result set of a PL/ SQL function call in a dialog box

    Hello,
    I am calling a PL/ SQL function from Apex, which returns - List of varchar.
    In Apex, it should show this list of varchar and "Yes" and "No" buttons on a message window.
    Can you please suggest a way to achieve the same.
    Thanks,
    Girish

    Hello,
    This application process "vrl_popup" is to get the values from PL/ SQL function. For popup window - confirm(). Also declared the LV_list as Application Item.
    Which is coded in the region part of the button. After pressing this button popup window should come with the list.
    <script type="text/javascript">
    <!--
    function doAjaxRequestParam( process, parameter)
    var ajaxRequest = new htmldb_Get(null,&APP_ID.,'vrl_popup='+process,0);
    ajaxRequest.add('lv_list', parameter );
    var jsonResult = eval('('+ ajaxRequest.get() +')');
    return jsonResult;
    var answer = confirm ("can try this?")
    alert (v_list)
    if (answer)
    alert ("done")
    else
    alert ("Unsuccessful")
    // -->
    </script>
    In apex I created following Application process by name = vrl_popup,
    declare
    lv_List varchar2(2000) := '';
    begin
    begin
    lv_List := select vrl_type_process_pkg.get_regd_reg_lste() from dual;
    exception when no_data_found then null;
    end;
    htp.prn(lv_List);
    end;
    Kindly help in fixing this.
    Edited by: Girish on Jun 17, 2010 12:57 AM

Maybe you are looking for