Passing String Which Has Single Quote Row/Value to a Function Returns Double Quoate

Hi, I'm getting weird thing in resultset. When I pass String which has single quote value in it to a split function , it returns rows with double quote. 
For example  following string:
'N gage, Wash 'n Curl,Murray's, Don't-B-Bald
Returns:
''N gage, Wash ''n Curl,Murray''s, Don''t-B-Bald
Here is the split function:
CREATE Function [dbo].[fnSplit] (
@List varchar(8000), 
@Delimiter char(1)
Returns @Temp1 Table (
ItemId int Identity(1, 1) NOT NULL PRIMARY KEY , 
Item varchar(8000) NULL 
As 
Begin 
Declare @item varchar(4000), 
@iPos int 
Set @Delimiter = ISNULL(@Delimiter, ';' ) 
Set @List = RTrim(LTrim(@List)) 
-- check for final delimiter 
If Right( @List, 1 ) <> @Delimiter -- append final delimiter 
Select @List = @List + @Delimiter -- get position of first element 
Select @iPos = Charindex( @Delimiter, @List, 1 ) 
While @iPos > 0 
Begin 
-- get item 
Select @item = LTrim( RTrim( Substring( @List, 1, @iPos -1 ) ) ) 
If @@ERROR <> 0 Break -- remove item form list 
Select @List = Substring( @List, @iPos + 1, Len(@List) - @iPos + 1 ) 
If @@ERROR <> 0 Break -- insert item 
Insert @Temp1 Values( @item ) If @@ERROR <> 0 Break 
-- get position pf next item 
Select @iPos = Charindex( @Delimiter, @List, 1 ) 
If @@ERROR <> 0 Break 
End 
Return 
End
FYI: I'm getting @List value from a table and passing it as a string to split function.
Any help would be appreciated!
ZK

fixed the issue by using Replace function like
Replace(value,'''''','''')
Big Thanks Patrick Hurst!!!!! :)
Though I came to another issue which I posted here:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/a26469cc-f7f7-4fb1-ac1b-b3e9769c6f3c/split-function-unable-to-parse-string-correctly?forum=transactsql
ZK

Similar Messages

  • SSRS Report Returning Double Quote string from a Single Quote String

    Hi, I'm getting weird thing in resultset from SSRS report when executed. When I pass parameter to a report, which passes String that has single quote value to a split function , it returns rows with double quote. 
    For example  following string:
    'N gage, Wash 'n Curl,Murray's, Don't-B-Bald
    Returns: 
    ''N gage, Wash ''n Curl,Murray''s, Don''t-B-Bald
    through SSRS report.
    Here is the split function Im using in a report.
    CREATE Function [dbo].[fnSplit] (
    @List varchar(8000), 
    @Delimiter char(1)
    Returns @Temp1 Table (
    ItemId int Identity(1, 1) NOT NULL PRIMARY KEY , 
    Item varchar(8000) NULL 
    As 
    Begin 
    Declare @item varchar(4000), 
    @iPos int 
    Set @Delimiter = ISNULL(@Delimiter, ';' ) 
    Set @List = RTrim(LTrim(@List)) 
    -- check for final delimiter 
    If Right( @List, 1 ) <> @Delimiter -- append final delimiter 
    Select @List = @List + @Delimiter -- get position of first element 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    While @iPos > 0 
    Begin 
    -- get item 
    Select @item = LTrim( RTrim( Substring( @List, 1, @iPos -1 ) ) ) 
    If @@ERROR <> 0 Break -- remove item form list 
    Select @List = Substring( @List, @iPos + 1, Len(@List) - @iPos + 1 ) 
    If @@ERROR <> 0 Break -- insert item 
    Insert @Temp1 Values( @item ) If @@ERROR <> 0 Break 
    -- get position pf next item 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    If @@ERROR <> 0 Break 
    End 
    Return 
    End
    FYI: I'm getting @List value from a table and passing it as a string to split function. 
    Any help would be appreciated!
    ZK

    Another user from TSQL forum posted this code which is returning the same resultset but when I execute both codes in SQL server it works and return single quote as expected.
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/8d5c96f5-c498-4f43-b2fb-284b0e83b205/passing-string-which-has-single-quote-rowvalue-to-a-function-returns-double-quoate?forum=transactsql
    CREATE FUNCTION dbo.splitter(@string VARCHAR(MAX), @delim CHAR(1))
    RETURNS @result TABLE (id INT IDENTITY, value VARCHAR(MAX))
    AS
    BEGIN
    WHILE CHARINDEX(@delim,@string) > 0
    BEGIN
    INSERT INTO @result (value) VALUES (LEFT(@string,CHARINDEX(@delim,@string)-1))
    SET @string = RIGHT(@string,LEN(@string)-CHARINDEX(@delim,@string))
    END
    INSERT INTO @result (value) VALUES (@string)
    RETURN
    END
    GO
    ZK

  • Copying a table with the right-click menu in schema browser fails to copy comments when string has single quote(s) (ascii chr(39))

    Hi,
    I'm running 32-bit version of SQL Developer v. 3.2.20.09 build 09.87, and I used the built in context menu (right-clicking from the schema browser) today to copy a table.  However, none of the comments copied.  When I dug into the PL/SQL that the menu-item is using, I realized that it fails because it doesn't handle single quotes within the comment string.
    For example, I have a table named WE_ENROLL_SNAPSHOT that I wanted to copy as WE_ENROLL_SNAPSHOT_V1 (within same schema name)
    1. I right-clicked on the object in the schema browser and selected Table > Copy...
    2. In the pop-up Copy window, I entered the new table name "WE_ENROLL_SNAPSHOT_V1" and ticked the box for "Include Data" option.  -- The PL/SQL that the menu-command is using is in the "SQL" tab of this window.  This is what I extracted later for testing the issue after the comments did not copy.
    Result: Table and data copied as-expected, but no column or table comments existed.
    I examined the PL/SQL block that the pop-up window issued, and saw this:
    declare
      l_sql varchar2(32767);
      c_tab_comment varchar2(32767);
      procedure run(p_sql varchar2) as
      begin
         execute immediate p_sql;
      end;
    begin
    run('create table "BI_ETL".WE_ENROLL_SNAPSHOT_V1 as select * from "BI_ETL"."WE_ENROLL_SNAPSHOT" where '||11||' = 11');
    select comments into c_tab_comment from sys.all_TAB_comments where owner = 'BI_ETL' and table_name = 'WE_ENROLL_SNAPSHOT' and comments is not null;
    run('comment on table BI_ETL.WE_ENROLL_SNAPSHOT_V1 is '||''''||c_tab_comment||'''');
    for tc in (select column_name from sys.all_tab_cols where owner = 'BI_ETL' and table_name = 'WE_ENROLL_SNAPSHOT')
        loop
       for c in (select comments from sys.all_col_comments where owner = 'BI_ETL' and table_name = 'WE_ENROLL_SNAPSHOT' and column_name=tc.column_name)
       loop
       run ('comment on column BI_ETL.WE_ENROLL_SNAPSHOT_V1.'||tc.column_name||' is '||''''||c.comments||'''');
    end loop;
    end loop;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    end;
    The string of the table comment on WE_ENROLL_SNAPSHOT is this:
    WBIG table of frozen, point-in-time snapshots of Enrolled Students by Category/term/pidm. "Category" is historically, and commonly, our CENSUS snapshot; but, can also describe other frequencies, or categorizations, such as: End-of-Term (EOT), etc. Note: Prior to this table existing, Census-snapshots were stored in SATURN.SNAPREG_ALL. All FALL and SPRING term records prior-to-and-including Spring 2013 ('201230') have been migrated into this table -- EXCEPT a few select prior to Fall 2004 (200410) records where there are duplicates on term/pidm. NO Summer snapshots existed in SNAPREG_ALL, but were queried and stored retroactively (including terms prior to Spring 2013) for the purpose of future on-going year-over-year analysis and comparison.
    Note the single quotes in the comment: ... ('201230')
    So, in the above PL/SQL line 11 grabs this string into "c_tab_comment", but then line 12 fails because of the single quotes.  It doesn't know how to end the string because the single quotes in the string are not "escaped", and this messes up the concatenation on line 12.  (So, then no other column comments are created either because the block throws an error, and goes to line 22 for the exception and exits.)
    When I modify the above PL/SQL as my own anonymous block like this, it is successful:
    declare
      c_tab_comment VARCHAR2(32767);
    begin
    SELECT REPLACE(comments,chr(39),chr(39)||chr(39)) INTO c_tab_comment FROM sys.all_TAB_comments WHERE owner = 'BI_ETL'   AND table_name = 'WE_ENROLL_SNAPSHOT'  AND comments IS NOT NULL;
    EXECUTE IMMEDIATE 'comment on table BI_ETL.WE_ENROLL_SNAPSHOT_V1 is '''||c_tab_comment||'''';
    for tc in (select column_name from sys.all_tab_cols where owner = 'BI_ETL' and table_name = 'WE_ENROLL_SNAPSHOT')
        loop
       for c in (select REPLACE(comments,chr(39),chr(39)||chr(39)) comments from sys.all_col_comments where owner = 'BI_ETL' and table_name = 'WE_ENROLL_SNAPSHOT' and column_name=tc.column_name)
       loop
       EXECUTE IMMEDIATE 'comment on column BI_ETL.WE_ENROLL_SNAPSHOT_V1.'||tc.column_name||' is '||''''||c.comments||'''';
    end loop;
    end loop;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    end;
    On lines 4 and 8 I wrapped the "comments" from sys.all_tab_comments and sys.all_col_comments with a replace command finding every chr(39) and replacing with chr(39)||chr(39). (On line 8 I also had to alias the wrapped column as "comments" so line 10 would succeed.)
    Is this an issue with SQL Developer? Is there any chance that the menu-items can handle single quotes in comment strings? ... And, of course this makes me wonder which other context menu commands in the tool might have a similar issue.
    Thoughts?
    thanks//jacob

    PaigeT wrote:
    I know about quick drop, but it isn't helpful here. I want to be able to right click on a string or array wire, navigate to the string or array palette, and select the corresponding "Empty?" comparator. In this case, since I do actually know where those functions live, and I'm already using my mouse to right click on the wire, typing ctrl-space to open quick drop and then typing in the function name is actually more work than navigating to it in the palette. It would just be nice to have it on hand in the location I naturally go to look for it the first time. 
    I don't agree with this work flow.  Right hand on mouse, left hand on home keys.  Pressing CTRL + Space is done with the left hands, and then you could assign "ea" to "Empty Array" both of which is accessible with the left hand.  Darren posted a bunch of great shortcuts for the right handed developer.
    https://decibel.ni.com/content/docs/DOC-20453
    This is much faster than waiting for any right click menu navigation, even if it is found in the suggested subpalette.
    Unofficial Forum Rules and Guidelines - Hooovahh - LabVIEW Overlord
    If 10 out of 10 experts in any field say something is bad, you should probably take their opinion seriously.

  • Reading String within the single quotes

    Hi All,
    Can you please let me know, how to read a String within the sinle quote in line.
    I have to read a report into internal table and again from that I need to read a string within the single quote. Please help me in this.
    Thanks in Advance,
    Raghu

    I have the following code:
    REPORT  test.
    DATA:  v_test(05) TYPE c.
    v_test = ‘TTT’.
    I am getting this errror:
    Field “TTT” is unknown.  It is neither kin on e of the specified tables nor defined by a “DATA” statement.
    For some reason, my single quote is not being recognized from my keyboard.  I noticed that my emotion icons are not being displayed either (example:  I type and i do NOT get the smiley face on my end).
    Is there a button that I pressed that caused that?

  • String with embedded single quote

    Hi, all. We're trying to pass a string from one procedure to another, which will then do an EXECUTE IMMEDIATE on it. However, there are single quotes withing the string, and they're driving us nuts! This is what the concatenated string should look like when passed to the pw_execDDL procedure:
    insert into appimmunization.wsrprfs (inoc_id, proof, is_valid,proof_num) values ('MEAG', to_date('02-OCT-05','DD-MMM-YY'), 'Y',1);
    Here's the concatenation process that doesn't work, and there are functions being called within the string:
    chr_sql := 'insert into appimmunization.wsrprfs (inoc_id, proof, is_valid,proof_num) values (' || '''' || prm_inoc_id || '''' || ', ' || 'to_date(' || '''' || prm_proof1 || ''''||','||'''' ||'DD-MMM-YY'||''''||')' || ', ' || '''' || fw_is_proof_valid(prm_birth_date, prm_proof1) || '''' || ',1);';
    pw_execDDL(chr_sql); /* call the procedure to do the EXECUTE IMMEDIATE */
    Help! We've tried every combination -- using two single quotes together, three, and four, and still no luck. Thanks.

    insert into appimmunization.wsrprfs (inoc_id, proof,
    is_valid,proof_num) values ('MEAG',
    to_date('02-OCT-05','DD-MMM-YY'), 'Y',1);
    This statement can be made in a string with the following affectation:
    chr_sql := 'insert into appimmunization.wsrprfs (inoc_id, proof, is_valid,proof_num) values (''MEAG'', to_date(''02-OCT-05'',''DD-MMM-YY''), ''Y'',1)';
    Note please that each single quote in your original string must be specified using two single quotes and that is all. It is more readable and more easy to do it this way.
    Michel.

  • Trouble with inserting a string containing a single quote

    Using php with Oracle
    If I do the following two lines before sending my $Query string through the parse function
    $name = "Dominick's";
    $Query = "INSERT INTO customers (name) values ('$name')";
    it gives me the following error:
    Warning: Ora_Parse failed (ORA-00917: missing comma -- while processing OCI function OPARSE)
    If I try and force the single quote to be surrounded by double quotes and therefore not be confused:
    $name = "Dominick's";
    Query = "INSERT INTO customers (name) values (\"$name\")";
    Trying that yields the following error:
    Warning: Ora_Parse failed (ORA-01741: illegal zero-length identifier -- while processing OCI function OPARSE)
    Help
    Jeff

    If it is possible (and here it is) you should use str_replace instead of ereg_replaceThanks for the reminder about str_replace().
    $Query = "INSERT INTO customers (name) values ('".addSlashes($name)."')";This gives an invalid Oracle SQL statement, which will generally fail with
      ORA-01756: quoted string not properly terminatedFor Oracle, single quotes must be doubled, not escaped with backslash.
    Of the solutions to insert the data, I'd prefer using bind variables
    since no escaping or quote doubling is needed.
    -- CJ

  • String comparison having single quote

    hi
    i m comparing a string which already have a single quote like this
    var_name=khurram' shehzad
    select * from table where name=' var_name ';
    plz help me how to do it bcoz its creating probelm
    thanks and regards,

    Hi,
    I hope the below example will help you.
    SQL>SELECT 'abc''' FROM DUAL WHERE 'abc''' = 'abc''';
    'ABC
    abc'
    1 row selected.
    SQL>
    Regards

  • How to insert a string containing a single quote to the msql database? help

    how can i insert a string which contains a single quote in to database... anyone help
    Message was edited by:
    sijo_james

    Absolutely, Positively use a PreparedStatement. Do not use sqlEscape() function unless you have some overriding need (and I don't know what that could possibly be).
    There are 1000's of posts on the positive aspects of using a PreparedStatement rather than using a Statement. The two primary positive attributes of using a PreparedStatement are automatic escaping of Strings and a stronger security model for your application.

  • How to call a Query from widget which has mandatory variables/filter values

    Dear Gurus,
        I want to show data from BI query (BEX) in Wedget, which has variable/ Filter as input parameter.     Please tell me how add these parameters while calling query throgh web service.
    Regards,
    Aslam Khan

    Hi Aslam,
    Kindly refer to Page Number 49 u2013 23rd Point and Page 50 and 51 in the SAPEnterpriseWidgetDevelopmentGuide.pdf u2013 Which explains how to pass the Import / input Parameters.
    You can also refer these links u2013 [How to pass more than one value in RfcRequest ?;
    [how to bind an input field with an rfc input;
    Hope it helpsu2026
    Regards,
    Shilpa B.V

  • How to write a cursor to check every row of a table which has millions of rows

    Hello every one.
    I need help. please... Below is the script (sample data), You can run directly on sql server management studio.
    Here we need to update PPTA_Status column in Donation table. There WILL BE 3 statuses, A1, A2 and Q.
    Here we need to update PPTA_status of January month donations only. We need to write a cursor. Here as this is a sample data we have only some donations (rows), but in the real table we have millions of rows. Need to check every row.
    If i run the cursor for January, cursor should take every row, row by row all the rows of January.
    we have donations in don_sample table, i need to check the test_results in the result_sample table for that donations and needs to update PPTA_status COLUMN.
    We need to check all the donations of January month one by one. For every donation, we need to check for the 2 previous donations. For the previous donations, we need to in the following way. check
    If we want to find previous donations of a donation, first look for the donor of that donation, then we can find previous donations of that donor. Like this we need to check for 2 previous donations.
    If there are 2 previous donations and if they have test results, we need to update PPTA_STATUS column of this donatioh as 'Q'.
    If 2 previous donation_numbers  has  test_code column in result_sample table as (9,10,11) values, then it means those donations has result.
    BWX72 donor in the sample data I gave is example of above scenario
    For the donation we are checking, if it has only 1 previous donation and it has a result in result_sample table, then set this donation Status as A2, after checking the result of this donation also.
    ZBW24 donor in the sample data I gave is example of above scenario
    For the donation we are checking, if it has only 1 previous donation and it DO NOT have a result in result_sample table, then set this donation Status as A1. after checking the result of this donation also.
    PGH56 donor in the sample data I gave is example of above scenario
    like this we need to check all the donations in don_sample table, it has millions of rows per every month.
    we need to join don_sample and result_sample by donation_number. And we need to check for test_code column for result.
    -- creating table
    CREATE TABLE [dbo].[DON_SAMPLE](
    [donation_number] [varchar](15) NOT NULL,
    [donation_date] [datetime] NULL,
    [donor_number] [varchar](12) NULL,
    [ppta_status] [varchar](5) NULL,
    [first_time_donation] [bit] NULL,
    [days_since_last_donation] [int] NULL
    ) ON [PRIMARY]
    --inserting values
    Insert into [dbo].[DON_SAMPLE] ([donation_number],[donation_date],[donor_number],[ppta_status],[first_time_donation],[days_since_last_donation])
    Select '27567167','2013-12-11 00:00:00.000','BWX72','A',1,0
    Union ALL
    Select '36543897','2014-12-26 00:00:00.000','BWX72','A',0,32
    Union ALL
    Select '47536542','2014-01-07 00:00:00.000','BWX72','A',0,120
    Union ALL
    Select '54312654','2014-12-09 00:00:00.000','JPZ41','A',1,0
    Union ALL
    Select '73276321','2014-12-17 00:00:00.000','JPZ41','A',0,64
    Union ALL
    Select '83642176','2014-01-15 00:00:00.000','JPZ41','A',0,45
    Union ALL
    Select '94527541','2014-12-11 00:00:00.000','ZBW24','A',0,120
    Union ALL
    Select '63497874','2014-01-13 00:00:00.000','ZBW24','A',1,0
    Union ALL
    Select '95786348','2014-12-17 00:00:00.000','PGH56','A',1,0
    Union ALL
    Select '87234156','2014-01-27 00:00:00.000','PGH56','A',1,0
    --- creating table
    CREATE TABLE [dbo].[RESULT_SAMPLE](
    [test_result_id] [int] IDENTITY(1,1) NOT NULL,
    [donation_number] [varchar](15) NOT NULL,
    [donation_date] [datetime] NULL,
    [test_code] [varchar](5) NULL,
    [test_result_date] [datetime] NULL,
    [test_result] [varchar](50) NULL,
    [donor_number] [varchar](12) NULL
    ) ON [PRIMARY]
    ---SET IDENTITY_INSERT dbo.[RESULT_SAMPLE] ON
    ---- inserting values
    Insert into [dbo].RESULT_SAMPLE( [test_result_id], [donation_number], [donation_date], [test_code], [test_result_date], [test_result], [donor_number])
    Select 278453,'27567167','2013-12-11 00:00:00.000','0009','2014-01-20 00:00:00.000','N','BWX72'
    Union ALL
    Select 278454,'27567167','2013-12-11 00:00:00.000','0010','2014-01-20 00:00:00.000','NEG','BWX72'
    Union ALL
    Select 278455,'27567167','2013-12-11 00:00:00.000','0011','2014-01-20 00:00:00.000','N','BWX72'
    Union ALL
    Select 387653,'36543897','2014-12-26 00:00:00.000','0009','2014-01-24 00:00:00.000','N','BWX72'
    Union ALL
    Select 387654,'36543897','2014-12-26 00:00:00.000','0081','2014-01-24 00:00:00.000','NEG','BWX72'
    Union ALL
    Select 387655,'36543897','2014-12-26 00:00:00.000','0082','2014-01-24 00:00:00.000','N','BWX72'
    UNION ALL
    Select 378245,'73276321','2014-12-17 00:00:00.000','0009','2014-01-30 00:00:00.000','N','JPZ41'
    Union ALL
    Select 378246,'73276321','2014-12-17 00:00:00.000','0010','2014-01-30 00:00:00.000','NEG','JPZ41'
    Union ALL
    Select 378247,'73276321','2014-12-17 00:00:00.000','0011','2014-01-30 00:00:00.000','NEG','JPZ41'
    UNION ALL
    Select 561234,'83642176','2014-01-15 00:00:00.000','0081','2014-01-19 00:00:00.000','N','JPZ41'
    Union ALL
    Select 561235,'83642176','2014-01-15 00:00:00.000','0082','2014-01-19 00:00:00.000','NEG','JPZ41'
    Union ALL
    Select 561236,'83642176','2014-01-15 00:00:00.000','0083','2014-01-19 00:00:00.000','NEG','JPZ41'
    Union ALL
    Select 457834,'94527541','2014-12-11 00:00:00.000','0009','2014-01-30 00:00:00.000','N','ZBW24'
    Union ALL
    Select 457835,'94527541','2014-12-11 00:00:00.000','0010','2014-01-30 00:00:00.000','NEG','ZBW24'
    Union ALL
    Select 457836,'94527541','2014-12-11 00:00:00.000','0011','2014-01-30 00:00:00.000','NEG','ZBW24'
    Union ALL
    Select 587345,'63497874','2014-01-13 00:00:00.000','0009','2014-01-29 00:00:00.000','N','ZBW24'
    Union ALL
    Select 587346,'63497874','2014-01-13 00:00:00.000','0010','2014-01-29 00:00:00.000','NEG','ZBW24'
    Union ALL
    Select 587347,'63497874','2014-01-13 00:00:00.000','0011','2014-01-29 00:00:00.000','NEG','ZBW24'
    Union ALL
    Select 524876,'87234156','2014-01-27 00:00:00.000','0081','2014-02-03 00:00:00.000','N','PGH56'
    Union ALL
    Select 524877,'87234156','2014-01-27 00:00:00.000','0082','2014-02-03 00:00:00.000','N','PGH56'
    Union ALL
    Select 524878,'87234156','2014-01-27 00:00:00.000','0083','2014-02-03 00:00:00.000','N','PGH56'
    select * from DON_SAMPLE
    order by donor_number
    select * from RESULT_SAMPLE
    order by donor_number

    You didn't mention the version of SQL Server.  It's important, because SQL Server 2012 makes the job much easier (and will also run much faster, by dodging a self join).  (As Kalman said, the OVER clause contributes to this answer).  
    Both approaches below avoid needing the cursor at all.  (There was part of your explanation I didn't understand fully, but I think these suggestions work regardless)
    Here's a SQL 2012 answer, using LAG() to lookup the previous 1 and 2 donation codes by Donor:  (EDIT: I overlooked a couple things in this post: please refer to my follow-up post for the final/fixed answer.  I'm leaving this post with my overlooked
    items, for posterity).
    With Results_Interim as
    Select *
    , count('x') over(partition by donor_number) as Ct_Donations
    , Lag(test_code, 1) over(partition by donor_number order by donation_date ) as PrevDon1
    , Lag(test_code, 2) over(partition by donor_number order by donation_date ) as PrevDon2
    from RESULT_SAMPLE
    Select *
    , case when PrevDon1 in (9, 10, 11) and PrevDon2 in (9, 10, 11) then 'Q'
    when PrevDon1 in (9, 10, 11) then 'A2'
    when PrevDon1 is not null then 'A1'
    End as NEWSTATUS
    from Results_Interim
    Where Test_result_Date >= '2014-01' and Test_result_Date < '2014-02'
    Order by Donor_Number, donation_date
    And a SQL 2005 or greater version, not using SQL 2012 new features
    With Results_Temp as
    Select *
    , count('x') over(partition by donor_number) as Ct_Donations
    , Row_Number() over(partition by donor_number order by donation_date ) as RN_Donor
    from RESULT_SAMPLE
    , Results_Interim as
    Select R1.*, P1.test_code as PrevDon1, P2.Test_Code as PrevDon2
    From Results_Temp R1
    left join Results_Temp P1 on P1.Donor_Number = R1.Donor_Number and P1.Rn_Donor = R1.RN_Donor - 1
    left join Results_Temp P2 on P2.Donor_Number = R1.Donor_Number and P2.Rn_Donor = R1.RN_Donor - 2
    Select *
    , case when PrevDon1 in (9, 10, 11) and PrevDon2 in (9, 10, 11) then 'Q'
    when PrevDon1 in (9, 10, 11) then 'A2'
    when PrevDon1 is not null then 'A1'
    End as NEWSTATUS
    from Results_Interim
    Where Test_result_Date >= '2014-01' and Test_result_Date < '2014-02'
    Order by Donor_Number, donation_date

  • Passing variable which has multiple values to cursor as parameter

    declare
    i varchar2(4000):='0';
    j varchar2(100):='0';
    cursor c1
    is
    (select * from gl_je_lines
    where period_name='Mar-10'
    and reference_10='WRITEOFF');
    cursor c2 (l_ref varchar2)
    is
    (select * from gl_je_lines
    where period_name='Mar-10'
    and reference_10='WRITEOFF'
    and reference_2 not in (l_ref));
    begin
    for cur_record in c1
    loop
    j:=cur_record.reference_2;
    end loop;
    i:= i||','''||j||'''';
    dbms_output.put_line(i);--here i has 254 values separated by ','
    for cash_rec in c2(i)
    loop
    dbms_output.put_line('this is loop 2');
    dbms_output.put_line(cash_rec.reference_2||','||cash_rec.reference_1);--Here this output is not displayed
    --i think the code in this cursor c2 is not executing
    --please tell me the solution
    end loop;
    end;
    I already use pl-sql table with array..it is not sufficietn to my requirement.because when i use it we must increment the index of that table ..so every time not in operator works in cursor2.so it shows wrong result
    From last three days i am working on this only please let me know as early as possible friends
    Edited by: 805567 on Oct 28, 2010 11:30 PM
    Edited by: 805567 on Oct 29, 2010 1:05 AM

    you said two cases
    in first case
    place my second cursor in first cursor
    if i place like that here i use not in operator
    so it prints for every value it will print not in of that value
    so it was wrong result
    i want not in all values
    in second case
    i took values from cursor not from table
    like as shown below
    declare
    credit_amount number:=0;
    debit_amount number:=0;
    v1 number:=0;
    v2 number:=0;
    v3 varchar2(500);
    v4 varchar2(500);
    v5 varchar2(240);
    v6 varchar2(240);
    v7 number;
    v8 varchar2(240);
    v9 varchar2(240);
    v10 number;
    v11 number;
    v12 varchar2(240);
    v13 varchar2(240);
    v14 varchar2(240);
    v15 number;
    v16 number;
    --This cursor is for liability records which are in GL not in AP
    cursor c1(p_header_id number,p_reference_2 varchar2,p_reference_4 varchar2)
    is
    (select
    jl.je_header_id "JE_HEADER_ID"
    ,jl.period_name "PERIOD"
    ,glcc.concatenated_segments "ACCOUNT_CODE"
    ,DECODE(jl.accounted_dr,null,0,jl.accounted_dr)"ACCOUNTED_DEBIT"
    ,DECODE(jl.accounted_cr,null,0,jl.accounted_cr) "ACCOUNTED_CREDIT"
    ,DECODE(jl.accounted_dr,null,0,jl.accounted_dr) - DECODE(jl.accounted_cr,null,0,jl.accounted_cr) "NET"
    ,glcc.CODE_COMBINATION_ID "CODE_COMBINATION_ID"
    ,jl.SET_OF_BOOKS_ID "SET_OF_BOOKS_ID"
    ,jl.PERIOD_NAME "PERIOD_NAME"
    ,DECODE(Jl.entered_dr,null,0,Jl.entered_dr)"ENTERED_DEBIT"
    ,DECODE(Jl.entered_cr,null,0,Jl.entered_cr) "ENTERED_CREDIT"
    ,jl.reference_1 "SUPPLIER"
    ,jl.reference_2 "INVOICE_ID"
    ,jl.reference_3 "CHECK_ID"
    ,jl.reference_4 "CHECK_NUMBER"
    ,jl.reference_5 "INVOICE_NUM"
    ,jl.reference_6 "'AP_PAYMT_JUST_INSERTED'"
    ,jl.reference_7 "set_of_books_id"
    ,jl.GL_SL_LINK_ID "GL_SL_LINK_ID"
    ,jl.REFERENCE_8 "INVOICE_DIST_LINE_NUMBER"
    ,jl.reference_9 "INVOICE_PAYMENT_ID"
    ,jl.REFERENCE_10 "LIABILITY"
    ,jl.TAX_CODE_ID "TAX_CODE_ID"
    ,jl.TAX_GROUP_ID "TAX_GROUP_ID"
    FROM
    gl_je_lines jl
    , apps.gl_code_combinations_KFV glcc
    , gl_je_headers jh
    WHERE
    jl.period_name='Mar-10'
    and glcc. code_combination_id in (1016,1296,1298)
    and jh.je_header_id = jl.je_header_id
    AND glcc.code_combination_id = jl.code_combination_id
    and jh.je_source = 'Payables'
    AND jl.je_header_id = p_header_id
    and jl.reference_2 = p_reference_2
    and jl.reference_4 = p_reference_4
    MINUS
    select
    ir.je_header_id
    , h.period_name "APPERIOD"
    ,g.CONCATENATED_SEGMENTS "AP ACCOUNT CODE"
    ,DECODE(l.accounted_dr,null,0,l.accounted_dr) "AP ACCOUNTED_DR"
    ,DECODE(l.accounted_cr,null,0,l.accounted_cr) "AP ACCOUNTED_CR"
    ,DECODE(l.accounted_dr,null,0,l.accounted_dr) - DECODE(l.accounted_cr,null,0,l.accounted_cr) "NET"
    ,l.CODE_COMBINATION_ID "AP_CCID"
    ,h.set_of_books_id
    ,h.PERIOD_NAME "PERIOD_NAME"
    ,DECODE(l.entered_dr,null,0,l.entered_dr)"ENTERED_DEBIT"
    ,DECODE(l.entered_cr,null,0,l.entered_cr) "ENTERED_CREDIT"
    ,l.reference1 "SUPPLIER"
    ,l.reference2 "INVOICE_Id"
    ,l.reference3 "reference_3"
    ,l.reference4 "reference_4"
    ,l.reference5 "INVOICE_NUM"
    ,l.reference6 "reference_6"
    ,l.reference7 "reference_7"
    ,l.GL_SL_LINK_ID "GL_SL_LINK_ID"
    ,l.REFERENCE8 "REFERENCE_8"
    ,l.reference9 "reference_9"
    ,l.REFERENCE10 "REFERENCE_10"
    ,l.TAX_CODE_ID "TAX_CODE_ID"
    ,l.TAX_LINK_ID "TAX_LINK_ID"
    from
    ap_ae_lines_all l,
    ap_ae_headers_all h,
    gl_code_combinations_kfv g
    ,gl_import_references ir
    where
    ir.gl_sl_link_id=l.gl_sl_link_id
    AND g.CODE_COMBINATION_ID = l.CODE_COMBINATION_ID
    and h.ae_header_id = l.ae_header_id
    AND h.period_name ='Mar-10'
    AND g.CODE_COMBINATION_ID in (1016,1296,1298)
    AND ir.JE_HEADER_ID = p_header_id
    and l.reference2 = p_reference_2
    and l.reference4 = p_reference_4);
    --This cursor is for writeoff records
    cursor c2
    is
    (select * from gl_je_lines
    where period_name='Mar-10'
    and reference_10='WRITEOFF'
    and reference_2 in ('525706','525600'));
    credit number:=0;
    debit number:=0;
    j varchar2(240);
    i varchar2(4000):='0';
    cursor c3 (p_invoice_id varchar2)
    is
    (select
    jl.je_header_id "JE_HEADER_ID"
    ,jl.period_name "PERIOD"
    ,glcc.concatenated_segments "ACCOUNT_CODE"
    ,DECODE(jl.accounted_dr,null,0,jl.accounted_dr)"ACCOUNTED_DEBIT"
    ,DECODE(jl.accounted_cr,null,0,jl.accounted_cr) "ACCOUNTED_CREDIT"
    ,DECODE(jl.accounted_dr,null,0,jl.accounted_dr) - DECODE(jl.accounted_cr,null,0,jl.accounted_cr) "NET"
    ,glcc.CODE_COMBINATION_ID "CODE_COMBINATION_ID"
    ,jl.SET_OF_BOOKS_ID "SET_OF_BOOKS_ID"
    ,jl.PERIOD_NAME "PERIOD_NAME"
    ,DECODE(Jl.entered_dr,null,0,Jl.entered_dr)"ENTERED_DEBIT"
    ,DECODE(Jl.entered_cr,null,0,Jl.entered_cr) "ENTERED_CREDIT"
    ,jl.reference_1 "SUPPLIER"
    ,jl.reference_2 "INVOICE_ID"
    ,jl.reference_3 "CHECK_ID"
    ,jl.reference_4 "CHECK_NUMBER"
    ,jl.reference_5 "INVOICE_NUM"
    ,jl.reference_6 "'AP_PAYMT_JUST_INSERTED'"
    ,jl.reference_7 "set_of_books_id"
    ,jl.GL_SL_LINK_ID "GL_SL_LINK_ID"
    ,jl.REFERENCE_8 "INVOICE_DIST_LINE_NUMBER"
    ,jl.reference_9 "INVOICE_PAYMENT_ID"
    ,jl.REFERENCE_10 "LIABILITY"
    ,jl.TAX_CODE_ID "TAX_CODE_ID"
    ,jl.TAX_GROUP_ID "TAX_GROUP_ID"
    FROM
    gl_je_lines jl
    , apps.gl_code_combinations_KFV glcc
    , gl_je_headers jh
    WHERE
    jl.period_name='Mar-10'
    and glcc. code_combination_id in (1016,1296,1298)
    and jh.je_header_id = jl.je_header_id
    AND glcc.code_combination_id = jl.code_combination_id
    and jh.je_source = 'Payables'
    and jl.reference_2 in (p_invoice_id)
    MINUS
    select
    ir.je_header_id
    , h.period_name "AP PERIOD"
    ,g.CONCATENATED_SEGMENTS "AP ACCOUNT CODE"
    ,DECODE(l.accounted_dr,null,0,l.accounted_dr) "AP ACCOUNTED_DR"
    ,DECODE(l.accounted_cr,null,0,l.accounted_cr) "AP ACCOUNTED_CR"
    ,DECODE(l.accounted_dr,null,0,l.accounted_dr) - DECODE(l.accounted_cr,null,0,l.accounted_cr) "NET"
    ,l.CODE_COMBINATION_ID "AP_CCID"
    ,h.set_of_books_id
    ,h.PERIOD_NAME "PERIOD_NAME"
    ,DECODE(l.entered_dr,null,0,l.entered_dr)"ENTERED_DEBIT"
    ,DECODE(l.entered_cr,null,0,l.entered_cr) "ENTERED_CREDIT"
    ,l.reference1 "SUPPLIER"
    ,l.reference2 "INVOICE_Id"
    ,l.reference3 "reference_3"
    ,l.reference4 "reference_4"
    ,l.reference5 "INVOICE_NUM"
    ,l.reference6 "reference_6"
    ,l.reference7 "reference_7"
    ,l.GL_SL_LINK_ID "GL_SL_LINK_ID"
    ,l.REFERENCE8 "REFERENCE_8"
    ,l.reference9 "reference_9"
    ,l.REFERENCE10 "REFERENCE_10"
    ,l.TAX_CODE_ID "TAX_CODE_ID"
    ,l.TAX_LINK_ID "TAX_LINK_ID"
    from
    ap_ae_lines_all l,
    ap_ae_headers_all h,
    gl_code_combinations_kfv g
    ,gl_import_references ir
    where
    ir.gl_sl_link_id=l.gl_sl_link_id
    AND g.CODE_COMBINATION_ID = l.CODE_COMBINATION_ID
    and h.ae_header_id = l.ae_header_id
    AND h.period_name ='Mar-10'
    AND g.CODE_COMBINATION_ID in (1016,1296,1298)
    and l.reference2 in (p_invoice_id)); --here if i put l.reference2  in (p_invoice_id)) it must show the details of
    -- of all.but it doesnot display sir
    --here if i put l.reference2 not in (p_invoice_id)) it shows that id also sir
    BEGIN
    for writeoff_rec in c2
    LOOP
    FOR Main_cur in c1(writeoff_rec.je_header_id,writeoff_rec.reference_2,writeoff_rec.reference_4)
    LOOP
    j:='0';
    IF writeoff_rec.accounted_dr is not null AND Main_cur.ACCOUNTED_CREDIT<>0
    THEN
    v10:=Main_cur.ACCOUNTED_CREDIT;
    credit_amount:= credit_amount+Main_cur.ACCOUNTED_CREDIT;
    ELSIF writeoff_rec.accounted_cr is not null AND Main_cur.ACCOUNTED_DEBIT<>0
    THEN
    v11:=Main_cur.ACCOUNTED_DEBIT;
    debit_amount:= debit_amount+Main_cur.ACCOUNTED_DEBIT;
    END IF;
    if c1%found then
    j:=Main_cur.INVOICE_ID;
    end if;
    END LOOP;
    -- i:=i||','||j;
    i:= i||','''||j||'''';
    END LOOP;
    dbms_output.put_line(i); --Here i got all invoiceids of varchar2 records without single qutations
    --its look like '0','23232','2324234' etc.
    for cash_clearing_cur in c3(i)--here is the problem i am sending i with 250 values separated by ',' is it correct
    loop
    v3:=0;
    v4:=0;
    v5:=0;
    v6:=0;
    v7:=0;
    v8:=0;
    v9:=0;
    v10:=0;
    v11:=0;
    v12:=0;
    v13:=0;
    v14:=0;
    v15:=0;
    v16:=0;
    credit:=credit+cash_clearing_cur.ACCOUNTED_CREDIT;
    debit:=debit+cash_clearing_cur.ACCOUNTED_DEBIT;
    v3:=cash_clearing_cur.JE_HEADER_ID;
    v4:=cash_clearing_cur.INVOICE_ID;
    v5:=cash_clearing_cur.CHECK_NUMBER;
    v6:=cash_clearing_cur.LIABILITY;
    v7:=cash_clearing_cur.CODE_COMBINATION_ID;
    v8:=cash_clearing_cur.PERIOD;
    v9:=cash_clearing_cur.ACCOUNT_CODE;
    v10:=cash_clearing_cur.ACCOUNTED_CREDIT;
    v11:=cash_clearing_cur.ACCOUNTED_DEBIT;
    v12:=cash_clearing_cur.SUPPLIER;
    v13:=cash_clearing_cur.CHECK_ID;
    v14:=cash_clearing_cur.INVOICE_NUM;
    v15:=cash_clearing_cur.GL_SL_LINK_ID;
    v16:=cash_clearing_cur.SET_OF_BOOKS_ID;
    DBMS_OUTPUT.PUT_LINE('HEAd '||v3||','||'inv_id '||v4||','||
    'chk_num '||v5||','||'ref10 '||v6||','||'CCID '||V7||','||'PED '||V8
    ||','||'acctcode '||v9||','||'acct_Ct '||V10
    ||','||'acct_Dt '||v11||','||'chk_id '||v13||','||'inv_num '||V14
    ||','||'link '||v15||','||'sob '||v16||','||'suplir '||V12);
    end loop;
    DBMS_OUTPUT.PUT_LINE( 'Dr Amt ' ||debit || 'Cr amt ' || credit );
    EXCEPTION
    when too_many_rows then
    dbms_output.put_line('Invalid no of rows');
    when no_data_found then
    dbms_output.put_line('no data found exception');
    when others then
    dbms_output.put_line('Other than Invalid no of rows');
    dbms_output.put_line(SQLERRM);
    END;
    /

  • Display rows which has only unique column values

    One of my table has the following data in it.
    ORDER_NO    IND_CODE
    1002              DNA
    1004              GEN
    1005    
    1007              DNA
    1008              DNA
    1009              GEN
    1010    
    1000              NULL
    1001              NULL
    1003              NULL
    1006              NULL
    1000              ZZZ
    1005              ZZZ
    I just want to display the rows with unique ORDER_NO.
    Sarvan

    You have 1000 as duplicate values in the column. But both have different indcode.
    Select distinct order_no from [table name]
    If you need combination of order_no and ind_code as unique then .
    Select distinct order_no, ind_code from [table name]

  • How do I write an array of strings to a single Excel row?

    I'd like to write test data, as an array of strings, to an Excel file. Attached is my attempt to modify one of the Labview 6.1 example files. This modified example will write the data to the correct row, which is determined by serial # of the UUT, but to a new sheet for each unit. I'd like to do the same thing, but to just one sheet. This sheet's data would then be saved after 50 rows of collected test data.
    Thank you in advance,
    Tim Denson
    Attachments:
    Write Table To XL.vi ‏58 KB

    Sorry I didn't get back to faster on this. I've been out of town working and just really haven't had time.
    Yes,
    The Report Generation toolkit would make this very easy. If you have it, I'd suggest using it.
    The image shown below shows the five VIs from the toolkit that I've used to write to Excel.
    What this loop does is receive a string through a Queue, either open a
    template or open todays file, convert the tab delimited string to an
    array, write the array to the next line of the Excel file, Save (with
    todays date stamp if opened from the tempate) and close it. It's a good
    idea to always save and close teh file after each write if it's not
    being continuously written to. In this case, a new line will be written
    only once a minute or so. This lessens the chance of losing data if the
    machine locks up for some reason. Opening and closing does take time
    and can slow down a loop that needs to run at a certain rate. This loop
    actually runs in a background process and several other processes send
    data to it through the queue to be written. The queue can buffer
    several data streams if needed so you won't lose data if it's busy and
    you don't have to worry about two processes accessing the Excel sheet
    at the same time.
    Ed
    Message Edited by Ed Dickens on 02-18-2006 11:12 AM
    Ed Dickens - Certified LabVIEW Architect - DISTek Integration, Inc. - NI Certified Alliance Partner
    Using the Abort button to stop your VI is like using a tree to stop your car. It works, but there may be consequences.
    Attachments:
    RGTK Array to Excel.gif ‏14 KB

  • How to display string which has BSP elements correctly?

    Hi,
       I have a string variable lv_text which content is:
    <htmlb:group height = "100%"
                         width  = "100%" >
              <htmlb:groupHeader>
                <xhtmlb:toolbar id="toolbar1" >
                  <xhtmlb:toolbarItem placement="LEFT" >
                    <htmlb:textView design = "HEADER3"
                                    text   = "AAAA"/>
                  </xhtmlb:toolbarItem>
                </xhtmlb:toolbar>
              </htmlb:groupHeader>
              <htmlb:groupBody>
                <%
      if gv_if_dis_message = 'X'.
                %>
                <%@include file="message.htm" %>
                <%
      Endif.
                %>
              </htmlb:groupBody>
            </htmlb:group>
        I want to use it in my BSP page and display the content correctly. Because it has some BSP elements, so now it can not be displayed correctly. How to solve this problem?
        Thanks a lot!

    you cannot do this way. what you can do is call the factory method of the htmlb:<tab> to get the element and render the element to a string and you can now use this string in your bsp page.
    Regards
    Raja

  • Problem when passing string array in sessions showing null value

    i am trying to pass a string array but it is showing me the null value
    i think the the problem is seem to be in session.settAttribute("subject['"+i+"']",subject) in 2.login_action.jsp
    or in String sub1=(String) session.getAttribute("subject[0]"); in 3.user_home.jsp
    i have following three pages
    1.login.html
    2.login_action.jsp
    3.user_home.html
    1.login.html
    <html>
    <body>
    <form method="post" action="login_action.jsp">
    Username<input type="text" name="username"></input>
    <br>
    Password<input type="password" name="password"></input>
    <input type="submit" value="login"></input>
    </form>
    </body>
    </html>
    2.login_action.jsp
    <%@ page contentType="text/html"%>
    <%@ page import="java.sql.*" %>
    <%!
    String user,pwd;
    String subject[]=new String[10];
    int i,totalsubject;
    %>
    <%
    try
    user=request.getParameter("username");
    pwd=request.getParameter("password");
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:ods","scott","tiger");
    PreparedStatement ps = con.prepareStatement("select password from users where username='"+user+"'");
    ResultSet rs = ps.executeQuery();
    if(rs.next())
    if(rs.getString("password").equals(pwd))
    session.setAttribute("username",user);
    PreparedStatement ps2 = con.prepareStatement("select subject_id from allot_teachers where staff_id='"+user+"'");
                        ResultSet rs2 = ps2.executeQuery();          
                             while(rs2.next())
                             i=0;
                             subject[i]=rs2.getString(1);
    // if i display here the subjects in out.println(subject[i]) it is working fine
    // but in next redirected page it is showing null
                             session.setAttribute("subject['"+i+"']",subject[i]);
                             //out.println(subject[i]);
                             i++;
    response.sendRedirect("user_home.jsp");
    else
    out.println("error invalid username or password");
    else
    out.println("error invalid username or password");
    con.close();
    catch(Exception e)
    out.println(e);
    %>
    3. user_home.jsp
    <%@ page contentType="text/html"%>
    <%@ page import="java.sql.*" %>
    <html>
    <%
    String user,pwd,cat,cat1;
    String username=(String) session.getAttribute("username");
    if(username==null)
    response.sendRedirect("login.html");
    //just tried for first two subjects
    String sub1=(String) session.getAttribute("subject[0]");
    String sub2=(String) session.getAttribute("subject[1]");
    //here it is printing null
    out.println(sub1);
    //here it is printing null
    out.println(sub2);
    %>
    <form method="post" action="logout.jsp">
    <input type="submit" value="Logout"></input>
    </form>
    </html>
    Cheers & Regards
    sweety

    The name in getAttributre doesnt match the name in setAttribute.
    Note "subject[0]" is a string containing 10 chars, "subject" is a string containing 7 chars.
    Here is your code:
    session.setAttribute("subject",subject);
    String sub1=(String) session.getAttribute("subject[0]");

Maybe you are looking for