Substring query

Hi all.
I'm wondering if some of you sql experts can help me create a query to single out a value from an item code. The item code looks like this "name fabric color size" the number of spaces (parameters) is always 4 but number of characters in the different parameters is dynamic.
I would very much like a query that gives me the size parameter in its own column - like this:
"name fabric color size" | "size"
Can this be done with a query?
Appreciate all help.
Best regards, Runar Wigestrand.

Try something like this:
declare @s nvarchar(100)
declare @i int
set @s=(Select Itemcode From . . .)
set @i=charindex(' ',@s)
set @s= substring(@s,@i+1,100)
set @i=charindex(' ',@s)
set @s= substring(@s,@i+1,100)
set @i=charindex(' ',@s)
set @s= substring(@s,@i+1,100)
Select @s

Similar Messages

  • Leading zeroes substring query in SQL Server

    Can Someone please help me in padding leading zeroes for the months in End date
    Example: actual data is like    6222007
    ,11301998 in end date column the following query works fine for 11301998 and converts it as 19981130 which was correct.
    But 6222007
    fails because month has no leading zero and it converts it as 0076222 which is wrong.
    How can i make it as 20070622 with the following code
    select (case when replace (ltrim(rtrim(ltrim([end date]))), '|', '') in ('99999999','00000000') then NULL 
        else substring ([END DATE],5,4)+SUBSTRING([END DATE],1,2)+SUBSTRING([END DATE],3,2) end) as ConvEnd_date
    from AdventureWorks.dbo.[AccountTable]

    Something like:
    declare @i int = 6222007
    select @i%10000 year_number, @i/1000000 month_number, (@i/10000)%100 day_number
    select DATEFROMPARTS(@i%10000,@i/1000000,(@i/10000)%100)
    David
    David http://blogs.msdn.com/b/dbrowne/

  • Using (+) in a substr query

    Hi ,
    i have the original query as
    SELECT * FROM View1 A , View2 B
    WHERE A.ITEM_ID = B.ITEM_ID(+)
    values for ITEM_ID is ABC.01
    ABC.02 ... 99
    values for ITEM_NAME is ABC
    however, when i changed it to
    SELECT * FROM View1 A , View2 B
    WHERE SUBSTR(A.ITEM_ID ,1 ,INSTR(A.ITEM_ID) - 1) =
    SUBSTR(b.ITEM_ID ,1 ,INSTR(b.ITEM_ID) - 1)(+)
    It does not work
    how is it possible to use the substr together with the outer join clause besides , putting the ITEM_NAME as part of the source view ?
    please advise
    tks & rgds

    Hi ,
    This is my sample data
    View 1          View 2
    Item_id          Item_id
    Item Dec          Item Dec
    View1          View2
    AAA.01          AAA.01
    BBB.01          CCC.02
    CCC.01          
    i just simply want to link view1 to view2 via Item_id , however ,as the version
    in this case view1 is CCC.01 but view2 is CCC.02 , i would still want the data from view1 to be shown
    It is this reason that i am using substr but the system is complaining that i cannot use (+)
    I do know that if i simply add in the item name (i.e w/o the version) at view1 & view2 , then i do not need to use the substr but still i would like to know if i am using the substr , how may i use it together with the (+) operator if it's possible.
    appreciate your advise
    tks & rgds

  • Substring query question

    How can I improve this query to only insert the first 40 chars. Table1, column1 type is VARCHAR2(100), but I just need up to 40 chars.
    INSERT /*+ append */ INTO Table2 (column1) SELECT (column1) FROM (table1);
    COMMIT;

    Well really wat I want to do is extract the first word from a column that is less then 40chars, otherwise extract the first 40 chars. And I want to do this to thousands of records, inserting them into a new table.

  • Sort problem on dynamic query !!

    Hi,
    I have a dynamic query written in pl/sql, when I check "Sort" for each field in Report Attribute, error message raised up as "ORA-01785: ORDER BY item must be the number of a SELECT-list expression".
    If I do not check Sort, it works fine. In my apps I need all fields sorted by user, how to fix this problem?
    My query as below:
    declare
    query varchar2(2000):='select';
    s_class varchar2(1000);
    cursor c1 is select * from demo_preference;
    begin
    for c1_val in c1 loop
    if c1_val.login is not null then
    query := query ||' ' || 'login' || ',';
    end if;
    if c1_val.id is not null then
    query := query ||' ' || 'id' || ',';
    end if;
    end loop;
    query := SUBSTR(query, 1, length(query)-1);
    s_class := '(NVL(:P2_class, ''%'' || ''null%'') = ''%'' || ''null%'' OR
    EXISTS (SELECT 1 FROM apex_collections WHERE collection_name = ''P2CLASSCOL'' AND c001 = class))';
    query := query ||' ' || 'from ming.reg_report_view1 where'
    || ' ' || s_class;
    return(query);
    end;

    Maybe the internally mapped column used when you clicked on sort is not shown in the report. Try using aliases when you construct the query string, it could help apex internally in identifying a column even if its order changes for a different user. After all the column order in the code is dynamic and I guess even the no of columns displayed might vary both of which could make sorting on a column identified with a number, invalid.
    How about displaying the report query somewhere, so that you know what is the exact query being processed, it might give you better information about the problem.
    If the problem persists, then use a collection that is fetched those record using the same query string and change the report to refer the collection and then set column sorting on. This way apex would get confused on what columns are being sorted and it would just sort on a c001..c050 column as though it was a string(yes problems with number columns sorting when you do this).

  • SQL Query using bind variables

    Hi All,
    Can any one please explain me how oracle will parse the below substr query using the bind varaibles, just want to know what oracle does in the backend when processing the below substr query.
    SUBSTR(:CDR_RT,3,7)
    Regards,
    Deepti

    All queries are processed in the same way.
    The example I've used on this article: PL/SQL 101 : Cursors and SQL Projection
    demonstrates the steps that a query/cursor goes through.
    If you're wondering if the SUBSTR in your query is applied to the value being bound in, _before_ the query is executed, then you are mistaken, the value is bound in as it is, and the substr takes place as part of the execution of the query.

  • Urgent pl.  I want to extract float from string (%f %s) or (%s %f) separate

    I want to extract float from string (%f %s) or (%s %f) separated by tab, whitespace etc., Since I am using jdk1.3.1 I can't use regular expression can anybody suggest a simple (one or two or few line code - compact) to get the float in (sign+/-)#.#### format ignoring other characters ?
    I tried:
    e.g.,
    String d="4.000 [tab]4";
    source string resulted from "SUBSTRING query of mySQL" can be of :
    " -4.543 XYZ ",
    " XYZ -4.546 ",
    " xx-yy 6.58 3 ",
    "6.0 xxx yyy zzz",
    the expected results for float from the string should be:
    -4.543
    -4.546
    6.580
    6.000
    If String containing data separated by comma:
    e.g.,
    "4.120     1     ,
    AAXXFE     ,4.206     1     ,
         4.000     1,
         4.201     1,
         4.189     1,
         4.204     1,
    S     DDERSF-RSA"
    The result should be: "4.120,4.206,4.000,4.201,4.189,4.204,0.000"
    The string is created by:
    ResultSet rs1 = stmt.executeQuery(S1);
    while (rs1.next()) {  
    String d = rs1.getString("SUBSTRING(FIELD1,LOCATE(\""+s2[i]+"\",FIELD1)+"+ k_st + ","+ length+")");
    System.out.print(d+",");
    May be I don't know how to use the following:
    float f1 = Float.parseFloat(d);
    ===
    String pattern = "###.###";
    //float value = -2100.578f;
    DecimalFormat myFormatter = new DecimalFormat(pattern);
    String output = myFormatter.format(d);
    System.out.println(d+" " + pattern + " " + output);
    ===

    Hi
    You made the best choice. JRegex is closer to java.util.regex.* and fine works with excellent performance in any JVM version so you can use examples/tutorials from both JRegex and Java.Sun.Com to learn more about regular expression.
    About the regular expression in my last post, there are two capturing groups: the first for float numbers in IEEE format specification (also see Java Language Specification) and the second for any sequence of chars, groups using with any amount of blank spaces (spaces, tabs, etc :: see regular expression definition) as delimiter. The anchors "^" and "$" are being used to exactly match pattern in target string and you can relax this constraint as needed.
    How to use JRegex? no secrets!
    import jregex.*;
    // a float number and string with any blank delimiter
    String patternString ="^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)\s+(.*)$";
    Pattern pattern = new Pattern(patternString); // different from Sun regex package syntax
    // below is identical in both packages
    Matcher m = pattern.matcher(anyTargetString);
    if (m.matches()) {
      Double d = Double.parseDouble( m.group(1) );
      String scratch = m.group(2);
      // your stuff goes here
    ..Remember to put JRegex jarfile in classpath!
    Regards and Success.

  • How to Substr field in SAP Query.

    Dear Developer,
    How to substr any field in SAP Query ?
    Regards,
    Ujed.

    Hi Ujed,
    if SUBSTR stands for substring, then possibly your question may be how to get the substr method as konown in languages like php in ABAP.  If SAP Query points to a SAP query as created in transaction SQ01, then you should explain what you want to achieve.
    Note: Better ask a specific question and get am answer you can or which is already generalized.
    If I need a substr function, I'd create a functional method for that:
    method substr
      importing
        anyfield type any
        offset type i
        length type i
      returning substring type string.
      try.
        substring = anyfield+offset(length).
      catch cx_root.
    * handle error
      endtry.
    endmethod.
    Regards,
    Clemens

  • SUBSTR and INSTR query

    Hello all,
    I need help in simple query how can show only MCCODE
    SELECT SUBSTR('VMTOPIC=MCCODE', INSTR('VMTOPIC=MCODE', 'VMTOPIC=')+8,20) AS output  FROM DUAL;But also when i used
    SELECT SUBSTR('VMTOPIC=MCCODE', INSTR('VMTOPIC=MCODE', 'HHH')+8,20) AS output  FROM DUAL;show same results, what i need only if words begin with " VMTOPIC= " retrived characters after "VMTOPIC=".
    regards
    Dheya

    Hi, Dheya,
    Here's one way:
    SELECT  SUBSTR ( str
                , INSTR ( str || 'VMTOPIC='
                            , 'VMTOPIC='
                     ) + 8
                , 20    -- or omit this argument
                )       AS output 
    FROM    table_x
    ;where tabe_x.str is the string you need to test.
    You could also do this with REGEXP_SUBSTR or REGEXP_REPLACE, but you can do this easily enough without any slow regular expressions.
    973907 wrote:
    ... But also when i used
    SELECT SUBSTR('VMTOPIC=MCCODE', INSTR('VMTOPIC=MCODE', 'HHH')+8,20) AS output  FROM DUAL;show same results, what i need only if words begin with " VMTOPIC= " retrived characters after "VMTOPIC=".That's because 'HHH' wasn't found, and so INSTR returned 0. SUBSTR treats 0 like 1 in its 2nd argument, so, using that expresssion, not fnding the string is te same as finding it at position 1.
    Of couse, looking for 'HHH' in a string that cotains 'VMTOPIC=' isn't the problem here; the real problem is looking for 'VMTOPIC=' in a string that doesn't contain it.
    Making a special case when INSTR returns 0, as Solomon suggested, is one way to get around the problem. Another is what I posted above, which guarantees that INSTR will never return 0. If the 'VMTOPIC=' is not found in str, then lookng for it in str || 'VMTOPIC=' will cause INSTR to return a very high number; so high that SUBSTR will then return NULL.
    I hope this answers your question.
    If not, post CREATE TABLE and INSERT statements for a little sample data (maybe 5 rows), and the results you want from that data.
    Point out where the query above is producing the wrong results, and explain, using specific examples, how you get those results from the sample data in those places.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • SUBSTRING in query of queries

    Hi,
    In a query of queries, can we do something like:
    <cfquery name="differentValuesFirstGroup"
    dbtype="query">
    SELECT DISTINCT SUBSTRING(#firstGroup#,1,1)
    FROM attributes.query
    </cfquery>
    I've tried SUBSTRING, SUBSTR, Left, but none of them seems to
    work...
    Any idea?
    Thanks

    No. But there are other ways to accomplish that.

  • SubStr function in Universe on BEx Query

    Hi SAP BO experts,
    We have a universe based on SAP BEx Query with an object  "WBS Element",  a 24 Character field from which we need to resolve certain sections as different objects for reporting purpose.  One of the objects required is first 8 chars (WBS Project No.)  Following code is used in object definition. 
    <EXPRESSION>Substr(@Select(WBS Element\WBS Element), 1, 8)</EXPRESSION>
    Parsing is OK at universe level.
    Webi query without "WBS Project No" is running OK but when "WBS Project No" is used, I get an error - invalid MDX command (WIS 10901).
    What is the correct syntax?  Any input will be appreciated.
    Thanks in advance.
    Venkat

    You can-not return characteristics via <EXPRESSION> tag.
    In fact right now it is not possible to do substring and similar operations. You can only create objects which returns numeric
    value.
    Regards,
    Rohit

  • SubStr Issue with Query

    I will give a great thanks for help with this. I have a table with a number field called "lotnum". Each rows "lotnum" has a value of 1000, 1001, 1002, 1003....2000, 2001, 2003, ..etc.) The parent row is always the one ending in zero (i.e.: 1000, 2000, 12000, etc....are all the parents). The children all end in 1,2,3,4...etc.. My problem is that another field (let's call it "x_dev") should have a value for not only the parent but also the child, but they do not. I need a query that will help me compare the parent's "x_dev" value with the value of all of the childrens "x_dev" values to determine if they are the same or not.
    Sample Data:
    Lotnum x_dev
    1000 20
    1001 Null
    1002 Null
    2000 20
    2001 Null
    (i.e: compare 1000 (parent) with the children (1001 & 1002) to determine if the "x_dev" value is the same and if not set it equal to the parent. I know I will have to probably use instr or substr going from right to left since the only constant is that the last three digits represent the children. The remaining digits are the parent (1, 10, 100, 1000), so the value could range from 1000 - 1000000)
    Thanks alot
    Edited by: kirkladb on Jul 14, 2012 12:09 PM

    select  t1.lotnum,
            t2.lotnum parent_lotnum,
            t1.dev_x,
            t2.dev_x parent_dev_x
      from  tbl t1,
            tbl t2
      where mod(t1.lotnum,1000) != 0
        and t2.lotnum = trunc(t1.lotnum / 1000) * 1000
        and lnnvl(t2.dev_x = t1.dev_x)
        LOTNUM PARENT_LOTNUM      DEV_X PARENT_DEV_X
          1002          1000                      20
          1001          1000                      20
          2001          2000                      20
    SQL> Or if this will be more readable to you:
    select  t1.lotnum,
            t2.lotnum parent_lotnum,
            t1.dev_x,
            t2.dev_x parent_dev_x
      from  tbl t1,
            tbl t2
      where mod(t1.lotnum,1000) != 0
        and t2.lotnum = trunc(t1.lotnum / 1000) * 1000
        and (t2.dev_x != t1.dev_x or t1.dev_x is null)
        LOTNUM PARENT_LOTNUM      DEV_X PARENT_DEV_X
          1002          1000                      20
          1001          1000                      20
          2001          2000                      20
    SQL> SY.

  • Sql query substring

    Hi,
    In my table i am having employee name like this
    EX:
    BOSE, Mr. BIRAT
    NANDY, Mr. AMITABHA
    The name before comma is the last name and after that is first Name
    Now i want to show in the front end like this for the above two
    Mr. BIRAT BOSE
    Mr. AMITABHA NANDY
    How to write an Sql query where you can get the Name before comma and place at the end of the name and remove the comma from it also for display purpose.
    Thanks,

    Non RegExp Solution
    SQL> with t
      2  as
      3  (
      4  select 'BOSE, Mr. BIRAT' name from dual union all
      5  select 'NANDY, Mr. AMITABHA' from dual
      6  )
      7  select name,
      8         substr(name, instr(name, ',', 1,1)+1) || ' ' || substr(name, 1, instr(name, ',',1,1)-1) new_name
      9    from t
    10  /
    NAME                NEW_NAME
    BOSE, Mr. BIRAT      Mr. BIRAT BOSE
    NANDY, Mr. AMITABHA  Mr. AMITABHA NANDY
    SQL>

  • Using substr function loses index. Query tune help

    Hi
    when i use substr function in the join condition it loses index and the query is slow. How to fix this problem or tune this query. These are the lines in the query.
    and substr(a.invoice_num,1,9) = l.invoice_num
    and substr(c.invoice_num,1,9) = mgr_apprv_lst.user_key
    and substr(c.invoice_num,1,9) = pbl_apprv_lst.user_key
    select
    pap.full_name employe_name,
         k.SEGMENT1 ||'.' ||k.segment2 Cost_Center,
         a.invoice_num Invoice_Number,
         b.item_description Line_Item,
         b.amount Amount,
         cc.trx_id Corporate_Card_Transaction_Id,
         cc.transaction_date Date_Charge_Incurred,
         cc.posted_date Date_Charge_Posted_To_USBank,
         cc.creation_date Date_Posted_To_IExpense,
         a.creation_date Expense_Report_Creation_Date,
         l.report_submitted_date Expense_Report_Submitted_Date,
         mgr_apprv_lst.activity_begin_date Managers_Approval_Begin_Date,
         mgr_apprv_lst.activity_end_date Managers_Approval_End_Date,
         pbl_apprv_lst.activity_begin_date AP_Approval_Begin_Date,
         pbl_apprv_lst.activity_end_date AP_Approval_End_Date,
         e.check_date Payment_Date_To_USBank,
         e.check_number Payment_Number,
         mgr_apprv_lst.activity_result_display_name Managers_Process_Result,
         pbl_apprv_lst.activity_result_display_name AP_Process_Result
    from
         ap_checks_all e,
         ap_invoice_payments_all d,
         ap_invoices_all c,
    ap_expense_report_headers_all a,
         ap_credit_card_trxns_all cc,
         per_all_people_f pap,
         ap_expense_report_headers_all l,
         ap_expense_report_lines_all b,
         gl_code_combinations k,
         (select ias1.user_key,
         ias1.activity_result_display_name,
         ias1.activity_begin_date,
         ias1.activity_end_date
    from wf_item_activity_statuses_v ias1,
    (select c1.invoice_num
         from ap_checks_all e1,
         ap_invoice_payments_all d1,
         ap_invoices_all c1
         where trunc(e1.check_date) between nvl(:From_Date, trunc(e1.check_date))
         and nvl(:To_Date, trunc(e1.check_date))
    and e1.org_id = 141
    and e1.void_date IS null
    and d1.check_id = e1.check_id
         and c1.invoice_id = d1.invoice_id) inv_lst1
    where ias1.item_type = 'APEXP'
    and ias1.user_key = inv_lst1.invoice_num
    and ias1.activity_name = 'AP_MANAGER_APPROVAL_PROCESS') mgr_apprv_lst,
    (select ias2.user_key,
         ias2.activity_result_display_name,
         ias2.activity_begin_date,
         ias2.activity_end_date
    from wf_item_activity_statuses_v ias2,
    (select c2.invoice_num
         from ap_checks_all e2,
         ap_invoice_payments_all d2,
         ap_invoices_all c2
         where trunc(e2.check_date) between nvl(:From_Date, trunc(e2.check_date))
         and nvl(:To_Date, trunc(e2.check_date))
    and e2.org_id = 141
    and e2.void_date IS null
    and d2.check_id = e2.check_id
         and c2.invoice_id = d2.invoice_id) inv_lst2
    where ias2.item_type = 'APEXP'
    and ias2.user_key = inv_lst2.invoice_num
    and ias2.activity_name = 'AP_PAYABLES_APPROVAL_PROCESS') pbl_apprv_lst
    where
    trunc(e.check_date) between nvl(:From_Date, trunc(e.check_date))
    and nvl(:To_Date, trunc(e.check_date))
    and e.org_id = 141
    and e.void_date IS null
    and d.check_id = e.check_id
    and c.invoice_id = d.invoice_id
    and a.invoice_num = c.invoice_num
    and a.source = 'CREDIT CARD'
    and a.employee_id = nvl(:Emp_id,a.employee_id)
    and a.report_header_id = b.report_header_id
    and cc.trx_id = b.credit_card_trx_id
    and pap.person_id = a.employee_id
    and pap.effective_start_date <= trunc(sysdate)
    and pap.effective_end_date >= trunc(sysdate)
    and k.code_combination_id = b.code_combination_id
    and k.segment2 between nvl(:From_Cost_Center,k.segment2)
    and nvl(:To_Cost_Center,k.segment2)
    and substr(a.invoice_num,1,9) = l.invoice_num
    and substr(c.invoice_num,1,9) = mgr_apprv_lst.user_key
    and substr(c.invoice_num,1,9) = pbl_apprv_lst.user_key

    Hi
    If I understood correctly your logic, and if the columns involved are of type varchar2, you can use the like operator:
    and a.invoice_num like l.invoice_num || '%'
    and c.invoice_num like mgr_apprv_lst.user_key  || '%'
    and c.invoice_num like pbl_apprv_lst.user_key  || '%'In this case, Oracle will be able to use the indexes. If they are numeric, you need to do something like:
    and a.invoice_num between l.invoice_num * 1000000
                                and l.invoice_num * 1000000 + 999999I hope this makes sense...
    Luis

  • Query substring and not numeric

    Using Oracle 10g.
    I need help with a query.. I need to get all the values where the first character is not a number. I know how to get the first character but other than that I'm lost.
    SELECT * FROM my_table where substr(EMP_ID, 1,1) is not numeric?

    Hi,
    user9179751 wrote:
    Using Oracle 10g.
    I need help with a query.. I need to get all the values where the first character is not a number. I know how to get the first character but other than that I'm lost.
    SELECT * FROM my_table where substr(EMP_ID, 1,1) is not numeric?Here's one way:
    SELECT     *
    FROM     my_table
    WHERE     INSTR ( '0123456789'
               , SUBSTR (emp_id, 1, 1)
               )       = 0
    ;Regular expressions and the LIKE operator can also do the job, perhaps with a little less coding, but they'll probably be less efficient. They can be very powerful tools, but you don't want to pay for that power when you're not using it.

Maybe you are looking for