Update statement using case

Hello my friends
I have one table "encompasses": continent,country,percentage
now the update should change the continent field, all "Europe" to "Asia" and all "Asia" to "America" and "America" to "Europe" by using case and just one update statement.
I wrote so and i got this error
Error starting at line 2 in command:
UPDATE encompasses
   SET continent=    
      CASE  WHEN continent='Europe'  THEN 'Asia'  
      WHEN continent='Asia'  THEN 'America' 
      WHEN continent='America' THEN 'Europe'
      END
Error report:
SQL Error: ORA-01407: cannot update ("intern"."ENCOMPASSES"."CONTINENT") to NULL
01407. 00000 -  "cannot update (%s) to NULL"
*Cause:   
*Action:please give me hints,thank u.
--  File created - Monday-May-13-2013  
  CREATE TABLE "intern"."ENCOMPASSES" ("COUNTRY" CHAR(2), "CONTINENT" VARCHAR2(20), "PERCENTAGE" NUMBER)
   COMMENT ON COLUMN "intern"."ENCOMPASSES"."COUNTRY" IS 'the country code'
   COMMENT ON COLUMN "intern"."ENCOMPASSES"."CONTINENT" IS 'the continent name'
   COMMENT ON COLUMN "intern"."ENCOMPASSES"."PERCENTAGE" IS 'percentage, how much of the area of a country belongs to the
            continent'
   COMMENT ON TABLE "intern"."ENCOMPASSES"  IS 'information to which continents a country belongs'
REM INSERTING into intern.ENCOMPASSES
SET DEFINE OFF;
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('cx','Asia',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('eg','Asia',10);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('ge','Asia',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('id','Asia',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('ad','Europe',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('al','Europe',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('at','Europe',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('ba','Europe',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('pa','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('pe','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('pm','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('pr','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('py','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('sr','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('sv','America',100);thank you, im using oracle 11g and ubuntu12
best,david
Edited by: 1003209 on 13-May-2013 10:12

1003209 wrote:
Hello my friends
I have one table "encompasses": continent,country,percentage
now the update should change the continent field, all "Europe" to "Asia" and all "Asia" to "America" and "America" to "Europe" by using case and just one update statement.
I wrote so and i got this error
Error starting at line 2 in command:
UPDATE encompasses
    SET continent=    
       CASE  WHEN continent='Europe'  THEN 'Asia'  
       WHEN continent='Asia'  THEN 'America' 
       WHEN continent='America' THEN 'Europe'
       END
Error report:
SQL Error: ORA-01407: cannot update ("intern"."ENCOMPASSES"."CONTINENT") to NULL
01407. 00000 -  "cannot update (%s) to NULL"
*Cause:   
*Action:This seems the column Continent has not null contraint on it, hence when there is a continent other than the three you mentioned above the case statement is evaluating it to null and hence failing e.g. if there is a record with continent = 'Antartica' it will try to update that as null.
so either add this:
WHERE continent in ('Europe' ,'Asia','America')this will update only for this continents and ignore other values.
If you want to update other continents as well then have a else condition in CASE statement to assign defualt value.
Regards,
Santosh

Similar Messages

  • Write an UPdate statement using the logic used in PL/SQL block (oracle 10g)

    Hi All,
    I have written the following PL/SQL block. I want to write an UPDATE statement using the logic used in the following PL/SQL block. can any one please help me out in this regards.
    DECLARE
       v_hoov_fag   gor_gold_post.hoov_flg%TYPE;
       v_b49n          gor_gold_post.b49n%TYPE;
       CURSOR c
       IS
          SELECT bs_id, loyalty_date, loyalty_period, contract_date
            FROM gor_gold_post
           WHERE tariff_code IN (169, 135, 136);
    BEGIN
       FOR rec IN c
       LOOP
          IF    (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period)
                        - SYSDATE) < 304
             OR (    TRUNC (  ADD_MONTHS (rec.loyalty_date, rec.loyalty_period)
                            - SYSDATE
                           ) IS NULL
                 AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2
          THEN
             v_hoov_flg := 1;
          ELSE
             v_hoover_flag := 99;
          END IF;
          IF    (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period)
                        - SYSDATE) < 121.6
             OR (    TRUNC (  ADD_MONTHS (rec.loyalty_date, rec.loyalty_period)
                            - SYSDATE
                           ) IS NULL
                 AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2
          THEN
             v_b49n := 1;
          ELSE
             v_b49n := 99;
          END IF;
          UPDATE gor_gold_post
             SET hoov_flg = v_hoov_flg,
                 b49n = v_b49n
           WHERE bs_id = rec.bs_id AND tariff_code IN (169, 135, 136);
          COMMIT;
       END LOOP;
    END;Thank you,

    Using case statement.
    UPDATE gor_gold_post
       SET hoov_flag = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 304
                                   OR
                                   (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
                                AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
                           THEN 1
                           ELSE 99
                         END,
           b49n      = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 121.6
                             OR
                             (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
                                AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
                           THEN 1
                           ELSE 99
                         END
    WHERE tariff_code IN (169, 135, 136);Note: Code not tested.

  • 'Missing select' error for update statement using WITH clause

    Hi,
    I am getting the below error for update statement using WITH clause
    SQL Error: ORA-00928: missing SELECT keyword
      UPDATE A
      set A.col1 = 'val1'
         where
      A.col2 IN (
      WITH D AS
      SELECT col2 FROM
      (SELECT col2, MIN(datecol) col3 FROM DS
      WHERE <conditions>
        GROUP BY PATIENT) D2
      WHERE
      <conditions on A.col4 and D2.col3>

    Hi,
    The format of a query using WITH is:
    WITH  d  AS
        SELECT  ...  -- sub_query
    SELECT  ...   -- main query
    You don't have a main query.  The keyword FROM has to come immediately after the right ')' that ends the last WITH clause sub-query.
    That explains the problem based on what you posted.  I can't tell if the real problem is in the conditions that you didn't post.
    I hope this answers your question.
    If not, post a complete test script that people can run to re-create the problem and test their ideas.  Include a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    In the case of a DML operation (such as UPDATE) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • Update statement with Case syntax

    I want to put case statement in an update statement using Oracle 10g
    I'm getting a syntax error on the last line Ora-00933: SQL command not properly ended
    Help please
    UPDATE EMP a
    SET EMP.TYPE = CASE
    WHEN 'Y' = 'A' THEN 'DIV'
    WHEN 'Y' = '1' THEN 'DEF'
    END CASE;

    Hi,
    Samim wrote:
    I want to put case statement in an update statement using Oracle 10g
    I'm getting a syntax error on the last line Ora-00933: SQL command not properly ended
    Help please
    UPDATE EMP a
    SET EMP.TYPE = CASE
    WHEN 'Y' = 'A' THEN 'DIV'
    WHEN 'Y' = '1' THEN 'DEF'
    END CASE;The closing keyword that corresponds to "CASE" is "END", not "END *CASE* ".
    The string 'Y' is never equal to 'A', or to '1'.
    If you have a column named y in the table, then you might want to say:
    UPDATE EMP
    SET EMP.TYPE = CASE
                        WHEN Y = 'A' THEN 'DIV'
                        WHEN Y = '1' THEN 'DEF'
                  END;I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statemnts to re-create your emp table as it exists before the UPDATE), and the results you want from that data (that is, the contents of the emp table after the UPDATE).

  • Is it possible that my update stats used only correct tables?

    Whenever there is a schedule maintenance run I receive a error:
    Executing the query "UPDATE STATISTICS [Perf].[PerfHourly_F65954CD35A54..." failed with the following error: "Table 'PerfHourly_F65954CD35A549E886A48E53F148F277' does not exist.". Possible failure reasons: Problems with the query, "ResultSet"
    property not set correctly, parameters not set correctly, or connection not established correctly.
    Is it possible that my update stats used only correct  tables?
    Thanks

    Use below script ...(change if required)
    USE [dbname]
    go
    DECLARE @mytable_id INT
    DECLARE @mytable VARCHAR(100)
    DECLARE @owner VARCHAR(128)
    DECLARE @SQL VARCHAR(256)
    SELECT @mytable_id = MIN(object_id)
    FROM sys.tables WITH(NOLOCK)
    WHERE is_ms_shipped = 0
    WHILE @mytable_id IS NOT NULL
    BEGIN
     SELECT @owner = SCHEMA_NAME(schema_id), @mytable = name
     FROM sys.tables
     WHERE object_id = @mytable_id
     SELECT @SQL = 'UPDATE STATISTICS '+ QUOTENAME(@owner) +'.' + QUOTENAME(@mytable) +' WITH ALL, FULLSCAN;'
     Print @SQL
     EXEC (@SQL)
     SELECT @mytable_id = MIN(object_id)
     FROM sys.tables WITH(NOLOCK)
     WHERE object_id > @mytable_id
      AND is_ms_shipped = 0
    END
    Or use below for required table only but it will not execute only generate script, make change as per ur requirements:
    SELECT X.*,
      ISNULL(CASE
        WHEN X.[Total Rows]<=1000
        THEN
          CASE
            WHEN [Percent Modified] >=20.0
            THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN  --20% Small Table Rule'
          END
        WHEN [Percent Modified] = 100.00
        THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  --100% No real Stats Rule'
        --WHEN X.[Rows Modified] > 1000
        --THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  --1000 Rows Modified Rule'
        ELSE
          CASE
            WHEN X.[Total Rows] > 1000000000 --billion rows
            THEN CASE
                   WHEN [Percent Modified] > 0.1
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 1B Big Table Rule'
                 END
            WHEN X.[Total Rows] > 100000000  --hundred million rows
            THEN CASE
                   WHEN [Percent Modified] > 1.0
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 100M Big Table Rule'
                 END
            WHEN X.[Total Rows] > 10000000   --ten million rows
            THEN CASE
                   WHEN [Percent Modified] > 2.0
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 10M Big Table Rule'
                 END
            WHEN X.[Total Rows] > 1000000    --million rows
            THEN CASE
                   WHEN [Percent Modified] > 5.0
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 1M Big Table Rule'
                 END
            WHEN X.[Total Rows] > 100000     --hundred thousand rows
            THEN CASE
                   WHEN [Percent Modified] > 10.0
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 100K Big Table Rule'
                 END
            WHEN X.[Total Rows] > 10000      --ten thousand rows
            THEN CASE
                   WHEN [Percent Modified] > 20.0
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 10K Big Table Rule'
                 END
            END
      END,'') AS [Statistics SQL]
    FROM (
    SELECT  DISTINCT
            DB_NAME()   AS [Database],
            S.name      AS [Schema Name],
            T.name      AS [Table Name],
            I.rowmodctr AS [Rows Modified],
            P.rows      AS [Total Rows],
            CASE
              WHEN I.rowmodctr > P.rows
              THEN 100
              ELSE CONVERT(decimal(8,2),((I.rowmodctr * 1.0) / P.rows * 1.) * 100.0)
            END AS [Percent Modified]
    FROM
            sys.partitions P
            INNER JOIN sys.tables  T ON P.object_Id = T.object_id
            INNER JOIN sys.schemas S ON T.schema_id = S.schema_id
            INNER JOIN sysindexes  I ON P.object_id = I.id
    WHERE P.index_id in (0,1)
      AND I.rowmodctr > 0
    ) X
    WHERE [Rows Modified] > 1000
    ORDER BY [Rows Modified] DESC
    Please click "Propose As Answer"
    if a post solves your problem, or "Vote As Helpful" if a post has been useful
    to you

  • Unable to execute an update statement using CallableStatement

    Hi there,
    I'm trying to run an update statement from JUnit using java.sql.CallableStatement and oracle.jbo.server.DBTransaction.
            String updateSql =
                "update footable set barcol=TO_DATE('12-SEP-09','dd-MM-yy') where bazcol = 505";
            try {
                statement =
                        applnModule.getDBTransaction().createCallableStatement(updateSql,
                                                                               2);
                int executeUpdate = statement.executeUpdate();
                AppsLogger.write(this,
                                 "# records UPDATED ------------------>" + executeUpdate,
                                 AppsLogger.SEVERE);
            } catch (SQLException s) {
                s.printStackTrace();
                Assert.fail("Encountered SQL Exception: " + s);
            } finally {
                try {
                    if (statement != null)
                        statement.close();
                } catch (SQLException s) {
            }Below is the exception I get when I run the above code. There is no problem with the SQL - it works fine from SQLDeveloper.
    java.lang.AssertionError: Encountered SQL Exception: java.sql.SQLDataException: ORA-01858: a non-numeric character was found where a numeric was expected
         org.junit.Assert.fail(Assert.java:91)
         sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         java.lang.reflect.Method.invoke(Method.java:597)
         org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
         org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:105)
         org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
         org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
         org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
         org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.invokeTestMethod(AtfJUnit4JTestCaseClassRunner.java:362)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.runMethods(AtfJUnit4JTestCaseClassRunner.java:272)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner$1.run(AtfJUnit4JTestCaseClassRunner.java:265)
         org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
         org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.run(AtfJUnit4JTestCaseClassRunner.java:262)Edited by: 911023 on Oct 2, 2012 11:28 AM
    Edited by: 911023 on Oct 2, 2012 11:30 AM

    Using case statement.
    UPDATE gor_gold_post
       SET hoov_flag = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 304
                                   OR
                                   (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
                                AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
                           THEN 1
                           ELSE 99
                         END,
           b49n      = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 121.6
                             OR
                             (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
                                AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
                           THEN 1
                           ELSE 99
                         END
    WHERE tariff_code IN (169, 135, 136);Note: Code not tested.

  • Update statement with Case

    Hi,
    I need to construct an SQL Update statement that uses a case statement.
    I was able to construct one:
    UPDATE tableB
    SET col1 = CASE WHEN (0, 0) = (SELECT col1, col2
    FROM tableA
    WHERE <tableA constraints> )
    THEN "this value"
    ELSE "that value"
    END
    WHERE <tableB constraints>;
    But what I need to do now is to have some comparison inside the CASE WHEN statement, like:
    UPDATE tableB
    SET col1 = CASE WHEN (SELECT col1 from tableA WHERE <tableA constraints> > 0
    AND
    SELECT col2 from tableA WHERE <tableA constraints> > 0
    THEN "this value"
    ELSE "that value"
    END
    WHERE <tableB constraints>;
    Basically, the case would need to pass two (or more) constraints before updating the valuefor tableB.
    By the way, I was able to do this with just one constraint inside the case statement, but I need to pass more than one constraint inside the case.
    Your inputs would be highly appreciated. Thanks.
    Regards,
    Edited by: BatutaBunsing on Jul 22, 2009 6:42 PM

    Example Test
    UPDATE emp
    SET    ename = CASE
                     WHEN (SELECT 1
                           FROM   dual
                           WHERE  1 = 1) > 0 --// condition TRUE
                          AND (SELECT 1
                               FROM   dual
                               WHERE  1 = 1) > 0  --// condition TRUE
                     THEN 'this value'
                     ELSE 'that value'
                   END
    WHERE  empno = 7369
    1 row updated.
    SQL> select * from emp ;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 this value CLERK           7902 17-DEC-80        800                    99
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
    UPDATE emp
    SET    ename = CASE
                      WHEN (SELECT 1
                            FROM   dual
                            WHERE  1 = 2) > 0 --// condition FALSE
                           AND (SELECT 1
                                FROM   dual
                                WHERE  1 = 1) > 0 --// condition TRUE
                      THEN 'this value'
                      ELSE 'that value'
                    END
    WHERE  empno = 7369
    1 row updated.
    SQL> select * from emp ;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 that value CLERK           7902 17-DEC-80        800                    99
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
    ...SS

  • Update statement with CASE and banding

    Hello Folks,
    I am stuck and am going nowhere.
    I have two tables
    MinuteCategory
    Minute
    MinuteCategory
    MinuteLookup
    MinuteCategoryId (surrogate key)
    MinuteLow
    MinuteHigh
    MinuteCategory
    Sample from Minute Lookup table ..
    1 1
    15 <15 min
    2 16
    30 <30 min
    3 31
    45 <45 min
    4 46
    60 <60 minutes
    5 61
    75 <1 hour 15 minutes
    I am trying to update the MinuteCategory column in the MinuteCategory table using the MinuteLookup table.
    For example if the minute = 33 then the corresponding lookup value would be 3 (from the lookup table), because the 
    33rd minute falls in between 31 min and 45 min and the corresponding surrogate key is 3
    Is this possible with an Update statement in SQL? The only thing i can think of is use case statement as the join key between
    the two tables but i don't think it's going to work :(
    UPDATE
    SET MinuteCategory = ml.MinuteCategoryId
    FROM MinuteCategory mc join MinuteLookup ml on mc.Minute = 
    CASE WHEN mc.Minute between ml.MinuteLow and ml.MinuteHigh THEN ml.MinuteCategoryId ELSE NULL
    END
    Would appreciate any help.
    SS

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    >> I have two tables <<
    Have you read any book on data, so you have some idea what a “<something>_category” means? THINK!! A minute is unit of temporal measurement. By definition, it cannot be a category. 
    There is no such thing as a “<something>_category_id”; a data element is a “<something>_category” or a “<something>_id”, as per basic data modeling. 
    Use a table of time slots set to one more decimal second of precision than your data. You can now use temporal math to add it to a DATE to TIME(1) get a full DATETIME2(0). Here is the basic skeleton. 
    CREATE TABLE Timeslots
    (slot_start_time TIME(1) NOT NULL PRIMARY KEY,
     slot_end_time TIME(1) NOT NULL,
     CHECK (start_time < end_time));
    INSERT INTO Timeslots  --15 min intervals
    VALUES ('00:00:00.0', '00:14:59.9'),
    ('00:15:00.0', '00:29:59.9'),
    ('00:30:00.0', '00:44:59.9'),
    ('00:45:00.0', '01:00:59.9'), 
    ('23:45:00.0', '23:59:59.9'); 
    Here is the basic query for rounding down to a time slot. 
    SELECT CAST (@in_timestamp AS DATE), T.start_time
      FROM Timeslots AS T
     WHERE CAST (@in_timestamp AS TIME)
           BETWEEN T.slot_start_time 
               AND T.slot_end_time;
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Problem in Update statement using Execute Immediate

    Hi All,
    I am facing problem in update statement.
    I am creating dynamic sql and use "execute immediate" statement to execute a update statement.
    But it is not updating any thing there in the table.
    I have created a query like :
    update_query='Update '|| Table_Name ||' t set t.process_status =''Y'' where t.tid=:A';
    Execute immediate update_query using V_Id;
    commit;
    But it is not updating the table.
    I have a question , is execute immediate only does insert and delete?
    Thanks
    Ashok

    SQL> select * from t;
                     TID P
                     101 N
    SQL> declare
      2     V_Id          number := 101;
      3     Table_Name    varchar2(30) := 'T';
      4     update_query  varchar2(1000);
      5  begin
      6     update_query := 'Update '|| Table_Name ||' t set t.process_status =''Y'' where t.tid=:A';
      7     Execute immediate update_query using V_Id;
      8     commit;
      9  end;
    10  /
    PL/SQL procedure successfully completed.
    SQL> select * from t;
                     TID P
                     101 Y                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Update Statement using SELECT statement

    The following select query return 1 record to me
    [code]
    select  deptno , dname, empno , max_date, max(v_num)
      from (select  d.deptno , d.dname , e.empno ,max (ver_date)  over(partition by d.id ,d.no) max_date  ,v_num
                from  emp e ,dept d
              where  e.deptno=d.deptno and e.dname = d.dname and e.empno=1 and d.deptno =3 )
    group by  deptno , dname, empno , max_date  
    [/code]
    Now I need to update the above value to the emp table itself
    In emp table for the empno=1  I need to update the columns mx_Date and v_num columns with the above last 2 columns in the select statement (max_date, max(v_num) )
    How can I write the update statement for this.
    Thank You

    Something like this
    merge into emp e1
    using (
              select deptno
                   , dname
                   , empno
                   , max_date
                   , max(v_num) v_num
                from (
                       select d.deptno
                            , d.dname
                            , e.empno
                            , max (ver_date)  over(partition by d.id , d.no) max_date 
                            , v_num
                         from emp e
                            , dept d
                        where e.deptno = d.deptno
                          and e.dname  = d.dname
                          and e.empno  = 1
                          and d.deptno = 3
               group
                  by deptno
                   , dname
                   , empno
                   , max_date  
          ) e2
       on (
            e1.empno = e2.empno
    when matched then
        update set e1.mx_date = e2.max_date,
                   e1.v_num   = e2.v_num

  • Problem with a sqlite update statement using variables

    Flash Builder/Flex 4
    I'm trying to create a routine that will allow me to change the name of an author in a sqlite table.
    I have this update statement which works with hardcoded data:
    //trace("updateName function newAuthorName: " + newAuthorName (returns Dusty));
    //trace("updateName function oldAuthorName: " + oldAuthorName (returns Kristin));
    updateStmt = new SQLStatement();
    updateStmt.sqlConnection = conn;
    var sql:String = "UPDATE tableName SET authorNameColumn = 'Dusty' WHERE authorNameColumn = 'Kristin' ";
    updateStmt.text = sql;
    updateStmt.execute();
    If I change the statement to
    "UPDATE tableName SET authorNameColumn  =" +  newAuthorName +  "WHERE authorNameColumn =" + oldAuthorName;
    I get SELECT error: SQLError: 'Error #3115: SQL Error.', details:'near 'authorNameColumn': syntax error'
    I've tried changing many things about this statement trying to isolate the problem, but it seems to not like the variables.

    Lee;
    Thanks for your help.
    I'm relatively new to this Flex stuff.
    I've been trying to fix this problem for hours and you know how it is when you keep looking at the same thing for too long.
    The article you linked to helped. I finally just copied the text from it and changed the variable name to my own.
    FINALLY!! I can go do something else now.
    Grins
    Kristin

  • Update Statement(with Case) in PL/SQL Block

    Can we use Oracle case syntax (In a Update SQL)in a PL/SQL Block .
    UPDATE table_name a
    SET a.colum1 =
    case when a.col2 IN (SELECT col1
    FROM table_name1 b )
    then 'Y'
    else 'N'
    end
    It throws me an Error of code PLS-00103(This error message is from the parser. It found a token (language element) that is inappropriate in this context.)
    Is there any alternative...
    Thanx in Advance
    null

    Alas, PL/SQL has own SQL parser, and this parser dosn't know about CASE expressions (at least, it's true up to Oracle 8.1.7).
    Try to use DECODE instead, something like
    UPDATE table_name a
    SET a.colum1 =
    SELECT decode(count(*),0,'N','Y)
    FROM table_name1 b
    WHERE b.col1=a.colum1

  • Update statement using function

    Environment: Win7 and SQL server 2008 R2
    Tools: SQL management tool 2008 R2
    Problem: I have been trying to update id numbers in the staging table. T-SQL statement updates all id number in the staging table, but what if the we have multiple records for the same person who we are assigning the ID to his/her record. It should generate
    one pn_id per ssn regadless if there are several records for the same individual. for example, my code assigns the following id: 
    Student table (ID, ssn, name, subject, grade, year)
    (288258466,192160792 , Sally Johnson, Math, A, 2014 )
    (176268917, 192160792, Sally Johnson, Spanish, B+, 2014 )
    (900303787, 770616858, Jessica Simpson, Spanish, B, 2014 )
    (704099635, 770616858, Jessica Simpson, IT, A, 2014 )
    (704099640, 444718562, Douglas Mike, IT, A, 2014 )
    (288258450, 31883459, Susan Jesson, IT, A, 2014 )
    (176268960, 260518681, Veronica Floris, IT, A, 2014 )
    The expected results should be as the following in the staging table
    Student table (ID, ssn, name, subject, grade, year)
    (288258466,192160792 , Sally Johnson, Math, A, 2014 )
    (288258466, 192160792, Sally Johnson, Spanish, B+, 2014 )
    (900303787, 770616858, Jessica Simpson, Spanish, B, 2014 )
    (900303787, 770616858, Jessica Simpson, IT, A, 2014 )
    (704099640, 444718562, Douglas Mike, IT, A, 2014 )
    (288258450, 31883459, Susan Jesson, IT, A, 2014 )
    (176268960, 260518681, Veronica Floris, IT, A, 2014 )
    My code:
    UPDATE a
    SET pn_id = (Select dbo.gen_id())
    from [dbo].[Staging_Table] a
    where SSN in (Select SSN from [dbo].[staging_Table]
    group by SSN having count(SSN) > 1)
    GO
    I also tried the following code but no success
    ;with cte
    As
    Select * , ROW_NUMBER() Over(Partition BY ssn Order by ssn) As MyCount
    from dbo.Staging_Table
    Select * into #a from cte where MyCount=1
    UPDATE a
    SET pn_id = (Select dbo.fn_gen_id())
    from staging_table a
    Full join #a b on a.ssn = b.ssn
    Drop table #a
    please help.

    I ran some tests and Sandra is correct, you don't always get the same value for all occurrences of the same SSN.
    After thinking about this, I think I understand why this happens.
    With functions, SQL is allowed to assume that multiple calls to a function in a single command with the same parameter values always return the same result.  That's why functions cannot use side-effecting functions and is not allowed to make changes
    to any table except table variables declared in the function.
    And SQL is allowed to rearrange the processing of a command in any manner it believes is most efficient as long as it returns the same result.  So even though the query I gave says first get a set of distinct SSN's and then calls the function only once
    for each SSN, it is valid for SQL to instead call the function once for each row in the original table since this function has no parameters and is therefore should return the same value on each call.  But since the function being called apparently (we've
    not seen the code of the function) returns different values on different calls, the same SSN could be assigned different values, but SQL would still be working correctly.
    Note that it would also be valid for SQL to notice that this function has no parameters and therefore should return the same value every time it is called within the same command and so just call the function once per execution of the command.  This
    would mean that every SSN would get the same ID.  As far as I can determine currently SQL does not do that but a different version in the future with a different optimizer might.
    Tom

  • Update statement using correlated partition over query - help asked please.

    A simple table:
    SQL> desc vs
    Name Null? Type
    COL1 VARCHAR2(10)
    COL2 NUMBER
    SQL> select * from vs;
    COL1 COL2
    A
    A
    B
    B
    B
    C
    D
    D
    E
    E
    E
    E
    E
    13 rows selected.
    I want to Update col2 with sequence number grouped by col1, in one step.
    EG. The seqno returned by:
    select col1, row_number() over (partition by col1 order by rowid) seqno
    from vs;
    COL1 SEQNO
    A 1
    A 2
    B 1
    B 2
    B 3
    C 1
    D 1
    D 2
    E 1
    E 2
    E 3
    E 4
    E 5
    13 rows selected.
    And UPDATE col2 with the seqno.
    The following worked:
    merge into vs v1
    using (select row_number() over (partition by col1 order by rowid)seqno,rowid from vs) v
    on (v1.rowid=v.rowid)
    when matched then update set v1.col2 = v.seqno
    when not matched then insert (v1.col1,v1.col2)
    values('Z',null);
    13 rows merged.
    SQL> select * from vs;
    COL1 COL2
    A 1
    A 2
    B 1
    B 2
    B 3
    C 1
    D 1
    D 2
    E 1
    E 2
    E 3
    E 4
    E 5
    13 rows selected.
    Can someone help with a simpler UPDATE or WITH ... statement?
    ==============
    This isn't urgent, just frustrated with syntax ;-)
    Best wishes of the season.

    Thank you for the reply.
    I've figured it out (with help).
    update vs a
    set col2 =
    (select seq from
    select rowid, row_number() over (partition by col1 order by rowid) as seq
    from vs
    ) b
    where a.rowid = b.rowid
    To complicate things (for my own interest)
    If some of the col2 were not null, and I had to sequence the null rows starting above the maximum value already used, I got this to work.
    SQL> select * from vs;
    COL1 COL2
    A 1
    A 2
    B 1
    B 2
    B 3
    C
    D 1
    D 2
    E 1
    E 10
    E
    E
    E
    update vs a
    set col2 =
    (select seq from
    select rowid, row_number() over (partition by col1 order by rowid)+
    (select max(nvl(col2,0)) from vs vsa where vsa.col1=vs.col1) as seq
    from vs
    where col2 is null
    order by col2 nulls last
    ) b
    where a.rowid = b.rowid
    where col2 is null;
    SQL> select * from vs;
    COL1 COL2
    A 1
    A 2
    B 1
    B 2
    B 3
    C 1
    D 1
    D 2
    E 1
    E 10
    E 11
    E 12
    E 13
    Might be helpful to someone else one day. Cheers everybody.

  • Update statement with case statement

    Hi
    The following code is thorwing an error like
    =====CODE==========
    BEGIN
    UPDATE emp SET SAL = CASE
    WHEN ENAME = 'SCOTT' THEN SAL = 300
    ELSE NULL;
    END CASE;
    END;
    =====ERROR=======
    ORA-06550: line 3, column 32:
    PL/SQL: ORA-00905: missing keyword
    ORA-06550: line 2, column 2:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 5, column 6:
    PLS-00103: Encountered the symbol "CASE" when expecting one of the following:
    ; 1.
    2. BEGIN
    3. UPDATE emp SET SAL = CASE
    4. WHEN ENAME = 'SCOTT' THEN SAL = 300
    5. ELSE NULL;
    Any suggession?
    Regards
    Balaji

    Hi,
    Yes you are right, but it is not working for the multiple case statement like the following code
    BEGIN
    UPDATE emp SET SAL = CASE
    WHEN ENAME='JONES' THEN '4';
    WHEN ENAME='BLAKE' THEN '5'
    WHEN ENAME='CLARK' THEN '6'
    WHEN ENAME='TURNER' THEN '7'
    WHEN ENAME='MILLER' THEN '8'
    WHEN ENAME='MARTIN' THEN '9'
    WHEN ENAME='WARD' THEN '10'
    WHEN ENAME='ADAMS' THEN '11'
    WHEN ENAME='JAMES' THEN '12'
    WHEN ENAME='SMITH' THEN '13'
    ELSE NULL END;
    END;
    The above code show the following error
    ===========ERROR==========
    ORA-06550: line 3, column 29:
    PL/SQL: ORA-00905: missing keyword
    ORA-06550: line 2, column 2:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 4, column 2:
    PLS-00103: Encountered the symbol "WHEN" when expecting one of the following:
    ( begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    1. BEGIN
    2. UPDATE emp SET SAL = CASE
    3. WHEN ENAME='JONES' THEN '4';
    4. WHEN ENAME='BLAKE' THEN '5'
    5. WHEN ENAME='CLARK' THEN '6'
    Regards
    Balaji
    Edited by: 904493 on Jan 13, 2012 4:18 AM

Maybe you are looking for

  • How to write XMP changes back to Photoshop DOM in CS SDK?

    Hello, I'm learning to use the ActionScript library for XMP in conjunction with the CS SDK to build Photoshop panels. I see from the Extension Builder samples that the AssetFragger application demonstrates how to use XMP for annotating comments to im

  • French VAT Localization

    Hello, We already installed the ECE Payables / Receivables Register for Localization implementations. I would like to know if we can go further, meaning having the country specific vat report (i.e. in France, the french 3310-CA3 form, used for the mo

  • Date search help in module pool programming in 4.6C version

    Hi Experts, How can i have input help in my module pool screen, I gave the searh help EXT_DATE in the search help parameter of that screen's field parameter. But its not showing the input help. I m facing this issue in 4.6C. Please advise Thanks Yoge

  • Am I missing any syntax ?

    Hi, I am new to Dialog Prog, can you please let me know what is the prob in the below code.I have to call a Subscreen 5000 up on one condition. *&      Module  STATUS_4000  OUTPUT *       text MODULE status_4000 OUTPUT.   SET PF-STATUS 'PF4000'.   CA

  • 500MB of data? What?

    I just recently bought the iPhone 4S. My plan came with 500MB of data. I thought that was a fair amount, until a relative of my told me they had 7GB of data on their iPhone 4. I'm just wondering what 500MB will do for me, and if it's a lot? I use my