PL/SQL or Trigger

Hi guys,
Somebody help me to write trigger or pl/sql which automatically adds record in a table on the 1st day of every year.
Thanks

You can do it by
DBMS_JOB package or you can simply do it by korne shell script in unix as follows.
create newyrsql.ksh on unix prompt by following.
vi newyrsql.ksh
#!/bin/ksh
sqlplus -s scott/tiger@test << EOF
create table emp2006 as select * from emp;
-- OR next one
insert into emp (select * from empold);
exit
save the file.
create "newyrjob" file as follows on unix prompt
vi newyrjob
0 1 1 1 * newyrsql.ksh
save the file
Now add the job in crontab by following
crontab newyrjob
That's it, this way this job will run at 1 am on 1st january on every year
JP

Similar Messages

  • Can I call a Java program from a SQL Server Trigger?

    Hello,
    I want to encrypt some data in a database column in SQL Server. Today I am using java code to encrypt the value and store it in the database using JDBC.
    Now I want to use a VB client to store the encrypted value in the SQL Server DB. Since the encryption is handled by a java class, can I write a trigger in SQL Server that while inserting the raw data, calls the java class for encrypting the value and then inserts the encrypted value into the column?
    In general, is it possible to call a java class from a SQL Server trigger?
    Thanks
    Bipin

    Here are 3 examples of code for insert, update and delete:
    CREATE TRIGGER [PLI_INSERT_TRIGGER] ON [dbo].[PLI]
    FOR INSERT
    AS
    Declare @cmd sysname, @code sysname, @list sysname
         Select @code = PLI_K_COD, @list = PLI_K_LISTINO from inserted
         Set @cmd = 'java mirrorDb.Copy PLI INSERT ' + @code + ' ' + @list
         EXEC master..xp_cmdshell @cmd
    CREATE TRIGGER [PLI_UPDATE_TRIGGER] ON [dbo].[PLI]
    FOR UPDATE
    AS
    Declare @cmd sysname, @code sysname, @list sysname
         Select @code = PLI_K_COD, @list = PLI_K_LISTINO from inserted
         Set @cmd = 'java mirrorDb.Copy PLI UPDATE ' + @code + ' ' + @list
         EXEC master..xp_cmdshell @cmd
    CREATE TRIGGER [PLI_DELETE_TRIGGER] ON [dbo].[PLI]
    FOR DELETE
    AS
    Declare @cmd sysname, @code sysname, @list sysname
         Select @code = PLI_K_COD, @list = PLI_K_LISTINO from deleted
         Set @cmd = 'java mirrorDb.Copy PLI DELETE ' + @code + ' ' + @list
         EXEC master..xp_cmdshell @cmd
    you must go "sql server entreprise manager" right click on the table you want to add triggers and select: all activities, manage triggers.
    You have 3 examples: for an insert, for an update and for a delete
    ON [dbo].[PLI] specify the table on which you want to setup trigger.
    FOR DELETE, INSERT, UPDATE specify the event.
    The Declare statement create the variables in which I want to put some values to pass to the java program, for example which table, which event, which key fields.
    the "Select @code = PLI_K_COD, @list = PLI_K_LISTINO from inserted" set the variables with the value of the columns of the table I am interested to read from my java program, for example the variable @code receive the value of the column pli_k_kod (is the key) of the table PLI.
    The "Set @cmd = 'java mirrorDb.Copy PLI DELETE ' + @code + ' ' + @list " prepared the variable @cmd with the java command followed by the package.classname and parameters.
    The EXEC launch the command to the operating system.
    Daniele

  • Executing dynamic SQL in trigger

    Hi !
    I just wanted to ask the community if it is ok using dynamic SQL
    with execute immediate in triggers, like:
    if (deleting or updating)
    and nvl(:old.col_val, 0) != 0
    then
    /* Update */
    sSql :=
    'update TMP_STAT_TEST ' ||
    'set col_val_' || to_char(:old.col_id) || ' = col_val_' ||
    to_char(:old.col_id) || ' - :1 ';
    execute immediate sSql using :old.col_val;
    end if;
    All dyn SQL inside the trigger does not reference the triggered
    table, so I will not get a mutating trigger.
    Thanks for your feedback.
    Stefan.

    Hi Andrew !
    I have a "master" table with date and amount and some more
    columns. I have a statistic table which must get updated
    accordingly each time the master table is changed (ins, upd,
    del). In this stats table there a cols like "sum_2000, sum_2001"
    etc. The dynamic statement depends on date to figure out the
    column name for the sum_yyyy cols, and amount will be
    added/subtracted. Of course there is a check that the trigger
    cannot handle when the year of the date is smaller than 2000 or
    greater than 2009.
    That's why I want to use dyn SQL.
    Stefan.

  • MS SQL-server trigger

    Hi,
    I wonder if there is anyone who know if there is any method as listen on a table in a ms sql-server. I want my program to run if a new row appear in the database.
    /Rikard

    Why would you need to do that? Put all theprocessing
    into the trigger, that's where it belongs.Possibly a bad assumption on my part, but since this
    is op posted in a java forum and said:
    "I want my program to run if a new row appear in the
    database"
    I assumed he has a program and that it is probably
    made with Java.
    I think nasch_ meant basically that perhaps the business logic that this 'app' does, really belongs in the database trigger.

  • PowerShell and SQL Server Trigger

    I had the following trigger written but apparently our IT department has not set up server/account or whatever needs to be done to use SQL Server's DB Mail.
    ALTER TRIGGER [dbo].[Faxiles_Trigger]
    ON [dbo].[DummyFQF]
    AFTER INSERT
    AS
    BEGIN
    DECLARE @tableHTML NVARCHAR(MAX) ;
    SET @tableHTML =
    N'<H1>Fax Error Report</H1>' +
    N'<table border="1">' +
    N'<tr><th>[FileID]</th>
    <th>[FaxID]</th>
    <th>[FilePath]</th></tr>' +
    CAST ( (
    SELECT
    td=T1.[FileID],' ',
    td=T1.[FaxID],' ',
    td=T1.[FilePath],' '
    FROM
    FaxQueueFiles as T1
    INNER JOIN
    FaxQueue as T2
    ON
    T1.[FaxID] = T2.[FaxID]
    WHERE
    T2.[DateAdded] between Dateadd(hour,-1,GETDATE()) and Getdate()
    AND
    T1.[FilePath] NOT LIKE 'C:\%'
    FOR XML PATH('tr'), TYPE
    ) AS NVARCHAR(MAX) ) +
    N'</table>' ;
    EXEC msdb.dbo.sp_send_dbmail
    @recipients='[email protected]',
    @subject = 'Fax Error Report',
    @body = @tableHTML,
    @body_format = 'HTML';
    END
    How can I instead make the trigger envoke/call a powershell script that can perform the same query and send an e-mail?
    Apparently we do have e-mail functionality for our scripts, so that part I can just copy/paste from a pre-existing script. What I don't know how to do (since I am brand new to powershell scripting) is save the results of a query into a HTML-f0rmatted table
    as the body of the e-mail like I did with SQL.
    Thanks in advance for any assistance you can provide.
    # Connect to the database.
    $dbConnSites = New-Object System.Data.SqlClient.SqlConnection("Data Source=localhost;Initial Catalog=Main;Integrated Security=SSPI");
    # Open database connection.
    $dbConnSites.Open();
    # Query String
    $dbQry_BadTIFs = "
    SELECT
    T1.[FileID], T1.[FaxID], T1.[FilePath]
    FROM
    Main.FaxQueueFiles as T1
    INNER JOIN
    FaxQueue as T2
    ON
    T1.FaxID = T2.FaxID
    WHERE
    T2.[DateAdded] between DATEADD(hour,-1,GETDATE()) and GETDATE()
    AND
    T1.[FilePath] NOT LIKE 'C:\%'
    # Create an SQL Command to execute the above query using the database connection object
    $dbGetBadTIFs = New-Object System.Data.SqlClient.SqlCommand(dbQry_BadTIFs, $dbConnSites);
    # Reader object to read the results of the executed SQL Command
    $dbGetBadTIFsReader = $dbGetBadTIFs.ExecuteReader();
    # Loop through the results of GetBadTIFs
    while ($dbGetBadTFIsReader.Read())
    # Close all the database connections
    $dbConnSites.Close();
    The above code is what I've come up with so far.... So within my while loop I presume the E-mail will some how be generated?
    Should I declare a new string object and concatenate within the loop?
    # Start the HTML Table for the e-mail
    $str_EmailBody = "
    <H1>Fax Error Report<H1>
    <TABLE border=`"1`">
    <TR>
    <TH>[FileID]</TH>
    <TH>[FaxID]</TH>
    <TH>[FilePath]</TH>
    </TR>
    </TABLE>
    # Loop through the results of GetBadTIFs
    # to fill out the HTML Table
    while ($dbRdr_GetBadTIFs.Read())
    $str_EmailBody += "???";
    # Finish the HTML Table for the e-mail
    $str_EmailBody += "
    </TR>
    </TABLE>";
    -Nothing to see. Move along.

    Hi Blacksaibot,
    If you want to query the sql cmd and send eamil with the result, please refer this script, to save the result of the query, plrease try to create a sql datatable:
    PowerShell Display Table In HTML Email
    If I have any misunderstanding, please let me know.
    Best Regards,
    Anna

  • PL/SQL for Trigger can't see a table?

    I am trying to write a simple log-in script that limits the number of log-in attempts that are allowed in a period of time. To support this I created a tiny 3 column table to record the failed log-in attempts -- but my WHEN-BUTTON-PRESSED PL/SQL trigger code can't seem to see the table? It always throws a SQL%NOTFOUND exception when I try to use this table. I've tried cnt, logons.cnt, and nw.logons.cnt to identify the columns but nothing has worked.
    What am I doing wrong?
    DECLARE
      dummy1 NUMBER;
    BEGIN
      SELECT nw.logons.cnt
      INTO dummy1
      FROM nw.logons
      WHERE nw.logons.userid = '2';
    LOGONS table in the NW schema
    USERID VARCHAR2(6 BYTE)
    LASTTIME DATE
    CNT NUMBER

    Oh GOD, I forgot to COMMIT. That is all it was. Sorry.

  • SQL 2012 Trigger bulk insert lock

    Hi
    I have built a proc which basically captures some invalid codes and what I would like to do is use a trigger to fire an email everytime this the table receives information .
    ;WITH MatchesCTE ( SK_Partial, Matchcode ) AS  
    (SELECT 1, '1234')
    SELECT * INTO match FROM MatchesCTE
    ALTER TRIGGER EmailInavildPartials1
       ON  [dbo].[match]
       AFTER INSERT
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        IF  (@@rowcount > 1)
        SET NOCOUNT ON;  
        --SELECT GETDATE() ;
        EXEC Send_email_Invalid_Partials1
       END
    ALTER PROCEDURE [dbo].[Send_email_Invalid_Partials1]
      AS
      DECLARE @p_body as nvarchar(max), @p_subject as nvarchar(max)
     DECLARE @p_recipients as nvarchar(max), @p_profile_name as nvarchar(max), @p_query as nvarchar(max),
     @p_subject_date as nvarchar(max), @fileName as nvarchar(max)
    SET @p_profile_name = N'DEV'
     SET @p_recipients = N'ROBERT@BLAH;'  
     Select @p_subject_date = (select DATENAME (weekday, getdate ()))+ ' ' + substring (convert(varchar,getdate(),12), 5,2) +'/' +  substring (convert(varchar,getdate(),12), 3,2)+ '/' +
       substring (convert(varchar,getdate(),12), 1,2)
     SET @filename = 'INVALID MATCH CODES ' + CONVERT(CHAR(8),GETDATE(),112)+ '.csv'
     SET @p_subject = @p_subject_date + N' INVALID MATCH CODES'
      SET @p_body = 'Please see the invaild Partials List.'
    SET @p_query = 'SET NOCOUNT ON;Select * FROM DATABASE..match '
     EXEC msdb.dbo.sp_send_dbmail
       @profile_name = @p_profile_name,
       @recipients = @p_recipients,
       @body = @p_body,
       @body_format = 'HTML',
       @subject = @p_subject,
       @query = @p_query,
       @attach_query_result_as_file = 1,
      @importance = 'High',
      @query_attachment_filename =@filename,
      @query_result_separator = ',',
      @query_result_no_padding = 1
    you''ll need to change
    @p_profile_name
    @p_recipients
    @p_query
    when you then run the following
    INSERT INTO match
    SELECT 1,'1234'
    UNION
    SELECT 1, '5678'
    It locks.    Is there any way around this ?  Any help would be great
    Thanks

    While I can debate the wisdom of this approach in general, as well as the selectivity of your logic with respect to the trigger, the rows inserted, the contents of the entire table - I won't. 
    The short story is that this approach will not work.  Your trigger fires within the context of an insert (presumably - perhaps a merge) statement that inserts some unknown number of rows into the target table.  Your trigger logic will then execute
    a procedure if more than one (but not one or zero rows) is inserted.  Your procedure will then attempt to execute a query against the same table and attempt to dump ALL rows in the table into a file for the email.  This "dumping" executes in a different
    process - hence the blocking. 
    Is it correct that your procedure will send the email with an attachment of ALL rows, not just the inserted ones (but ignore the insertion of just one row)?  I can't say.  It would be unusual but stranger things have been done.   To get
    around that you can use a locking hint as suggested - but that may not be what you desire depending on other factors (is anything else manipulating the contents of the table while this process is running? Are you certain of that answer after evaluating the
    range of possibilities?). 
    Perhaps the best approach is to use a very different one.  It appears that you insert rows into the table for a single purpose.  So why not just turn that process into the one that does the notification? 

  • Another sql query--trigger

    I want to write a trigger, usig DUAL table if possible, which shows me the name of a user who make changes in a table.
    User names are stored in "users" table (Smith, Jhon,etc,etc) and the trigger that I created looks like this:
    CREATE OR REPLACE TRIGGER ITEMS_after_update
    AFTER UPDATE
    ON ITEMS
    FOR EACH ROW
    DECLARE
    v_username varchar2(50);
    BEGIN
    -- Find username of person performing UPDATE into table
    -- SELECT useFNAME INTO v_username
    -- FROM USERS;
    -- Insert record into audit table
    INSERT INTO new_ITEMS
    ( ITEMKEY_new,
    ITEMKEY,
    ITEMNAME_new,
    ITEMNAME,SORTGROUP,
    SORTGROUP_new )
    VALUES
    ( :new.ITEMKEY,
    :OLD.ITEMKEY,
    :NEW.ITEMNAME,
    :OLD.ITEMNAME,
    :new.SORTGROUP,
    :OLD.SORTGROUP );
    END;
    If I'm using SELECT user INTO v_username FROM dual;
    instead of SELECT useFNAME INTO v_username FROM USERS I get the "company1" name and doesn't help.I would like to receive Jhon or Smith....
    Can anyone help me with this trigger ?
    Regards
    Robert B

    Where exactly are you trying to derive the user from? Based on your query
    "SELECT useFNAME INTO v_username FROM USERS;" that would bring back all rows from that table, which is not legitimate when using an INTO clause.
    Maybe you are wanting to do something like this?
    SELECT useFNAME INTO v_username
    from USERS where USERNAME = USER
    where USER is an Oracle function returning the user.

  • Dynamic SQL in trigger

    In a before insert/update on each row trigger I do the following:
    I loop over the user_tab_columns to get the column names for a table.
    In the loop I want to call :new.<columnname> with <columnname> a variable in which I stocked the current columnname.
    It has to be dynamic, a direct call to the column does not solve my problem.
    How can this be done?
    Thanks in advance!
    Marianne

    Have a look at
    re:Dynamic references to trigger vars :new and :old
    Cheers,
    Alex

  • SQL 2008 Trigger to handle multi rows scenario

    I have created below trigger to start logging the company changes from the table1 into another audit table. It works fine with single row but crashing with identical change with multiple rows. Can you please help me to update the trigger to handle multi-row
    scenario. Thanks.
    GO
    IF
    NOT EXISTS
    (SELECT
    * FROM sys.objects
    WHERE object_id
    = OBJECT_ID(N'[dbo].[Company_AuditPeriod]')
    AND type
    in (N'U'))
    CREATE
    TABLE [dbo].[Company_AuditPeriod](
          [Client] [varchar](25)
    NOT NULL,
          [Period] [varchar](25),
          [Table_Name] [varchar](25),
          [Field_Name] [varchar](25),
          [Old_Value] [varchar](25),
          [New_Value] [varchar](25),
          [User_ID] [varchar](25)
          [Last_Update] [datetime],
            [agrtid] [bigint]
    IDENTITY(1,1)
    NOT NULL,
    ON [PRIMARY]
    GO
    --create trigger
    SET
    QUOTED_IDENTIFIER ON
    GO
    CREATE
    TRIGGER [dbo].[Table1_Update]
    ON [dbo].[Table1]
    FOR
    UPDATE
    NOT
    FOR REPLICATION
    AS
    BEGIN
    DECLARE
          @status          
    varchar(3),
          @user_id   
    varchar(25),
          @period          
    varchar(25),
          @client          
    varchar(25),
          @last_update
    datetime
    DECLARE
          @Old_status      
    varchar(3),
          @Old_user_id     
    varchar(25),
          @Old_period      
    varchar(25),
          @Old_client      
    varchar(25)
    SELECT
          @status    
    = status,
          @user_id   
    = user_id,
          @period          
    = period,
          @client          
    = client,
          @last_update
    = last_update
    FROM Inserted
    SELECT
          @Old_status
    = status,
          @Old_user_id     
    = user_id,
          @Old_period      
    = period,
          @Old_client      
    = client
    FROM Deleted
    If @Old_status <> @status
    INSERT INTO Company_AuditPeriod
    VALUES ( @client, @period,
    'Table1',
    'period',@old_status, @status, @user_id, @last_update)
    END
    GO

    Sorry for the confusion.
    I just made sure the table name is same in sys.objects statement and create table statement (there was a typo)
    IF
    NOT EXISTS
    (SELECT
    * FROM sys.objects
    WHERE object_id
    = OBJECT_ID(N'[dbo].[Company_AuditPeriod]')
    AND type
    in (N'U'))
    CREATE
    TABLE [dbo].[ Company_AuditPeriod](
    Earlier you created Trigger on Company_AuditPeriod but
    We have to create trigger on Table1 please with multi row scenario. Thanks.
    --Company_AuditPeriod DDL
    GO
    IF
    NOT EXISTS
    (SELECT
    * FROM sys.objects
    WHERE object_id
    = OBJECT_ID(N'[dbo].[Company_AuditPeriod]')
    AND type
    in (N'U'))
    CREATE
    TABLE [dbo].[ Company_AuditPeriod](
          [Client] [varchar](25)
    NOT NULL,
          [Period] [varchar](25),
          [Table_Name] [varchar](25),
          [Field_Name] [varchar](25),
          [Old_Value] [varchar](25),
          [New_Value] [varchar](25),
          [User_ID] [varchar](25)
          [Last_Update] [datetime],
            [agrtid] [bigint]
    IDENTITY(1,1)
    NOT NULL,
    ON [PRIMARY]
    GO
    --Table1  DDL
    CREATE TABLE [dbo].[Table1](
    [bflag] [int] NOT NULL,
    [client] [varchar](25) NOT NULL,
    [copies] [int] NOT NULL,
    [cost_bio] [decimal](28, 8) NOT NULL,
    [cost_cpu] [decimal](28, 8) NOT NULL,
    [cost_dio] [decimal](28, 8) NOT NULL,
    [date_ended] [datetime] NOT NULL,
    [date_started] [datetime] NOT NULL,
    [description] [varchar](255) NOT NULL,
    [expire_days] [int] NOT NULL,
    [func_arg] [varchar](255) NOT NULL,
    [func_id] [int] NOT NULL,
    [ing_status] [int] NOT NULL,
    [invoke_time] [datetime] NOT NULL,
    [last_update] [datetime] NOT NULL,
    [mail_flag] [tinyint] NOT NULL,
    [me_mail_flag] [tinyint] NOT NULL,
    [module] [char](3) NOT NULL,
    [order_date] [datetime] NOT NULL,
    [orderno] [int] NOT NULL,
    [output_id] [int] NOT NULL,
    [poll_status] [char](1) NOT NULL,
    [printer] [char](16) NOT NULL,
    [priority] [char](1) NOT NULL,
    [priority_no] [int] NOT NULL,
    [process_id] [int] NOT NULL,
    [report_cols] [int] NOT NULL,
    [report_id] [varchar](255) NOT NULL,
    [report_name] [varchar](25) NOT NULL,
    [report_type] [char](1) NOT NULL,
    [server_queue] [char](12) NOT NULL,
    [status] [char](1) NOT NULL,
    [step_id] [char](8) NOT NULL,
    [system_name] [char](8) NOT NULL,
    [used_bio] [int] NOT NULL,
    [used_cpu] [int] NOT NULL,
    [used_dio] [int] NOT NULL,
    [user_id] [varchar](25) NOT NULL,
    [variant] [int] NOT NULL,
    [agrtid] [bigint] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
     CONSTRAINT [PK_acrrepord001] PRIMARY KEY NONCLUSTERED 
    [agrtid] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [INDEX]
    ) ON [PRIMARY]
    G0<o:p></o:p>
    --create trigger
    SET
    QUOTED_IDENTIFIER ON
    GO
    CREATE
    TRIGGER [dbo].[Table1_Update]
    ON [dbo].[Table1]
    FOR
    UPDATE
    NOT
    FOR REPLICATION
    AS
    BEGIN
    DECLARE
          @status          
    varchar(3),
          @user_id   
    varchar(25),
          @period          
    varchar(25),
          @client          
    varchar(25),
          @last_update
    datetime
    DECLARE
          @Old_status      
    varchar(3),
          @Old_user_id     
    varchar(25),
          @Old_period      
    varchar(25),
          @Old_client      
    varchar(25)
    SELECT
          @status    
    = status,
          @user_id   
    = user_id,
          @period          
    = period,
          @client          
    = client,
          @last_update
    = last_update
    FROM Inserted
    SELECT
          @Old_status
    = status,
          @Old_user_id     
    = user_id,
          @Old_period      
    = period,
          @Old_client      
    = client
    FROM Deleted
    If @Old_status <> @status
    INSERT INTO Company_AuditPeriod
    VALUES ( @client, @period,
    'Table1',
    'period',@old_status, @status, @user_id, @last_update)
    END
    go

  • Migrate a SQL-Server trigger

    Parse error in line 10, column 9. encountered INSERT.
    here is the code :
    CREATE TRIGGER delCategoria ON dbo.CATEGORIA
    FOR DELETE
    AS
    declare @usuarioTMS varchar(50)
         IF(UPPER(substring(APP_NAME(),1,4))='TMS\')
              set @usuarioTMS=UPPER(substring(APP_NAME(),1,50))
         Else
              set @usuarioTMS=UPPER(substring(SYSTEM_USER,1,50))
         INSERT INTO LOG
         (responsable,
         modulo,
         tipo,
         descripcion,
         datos_modificados)
         SELECT @usuarioTMS,
         'Administracion',
         'E',
         'Eliminación en Categoria',
         'Id CategorÃa: ' + convert(varchar,deleted.id_categoria) + ' - Nombre: ' + deleted.nombre
         FROM delete
    Colud you help me, i dont find any error in this code.      

    I think the last line should be 'FROM deleted'. Also try the parser option Allow 'Reserved Words' in table names, in this case the parser is confused by the table name LOG (you could change it to myLOG and edit the result back to LOG in the oracle model if you prefer.)
    I hope that gets you over that issue.
    Regards,
    Turloch
    Oracle Migration Workbench Team

  • Error in execuitng a trigger

    I am getting the following error in executing while executing the "dropping the trigger " , "creating a trigger " . or executing any stored proc .
    Please advise .
    I am on 10g Release 2 on Redhat linux .
    SQL> drop trigger logon_trigger ;
    drop trigger logon_trigger
    ORA-00604: error occurred at recursive SQL level 1
    ORA-01008: not all variables bound
    ORA-06512: at line 21

    I was able to resolve this by setting a undocumented parameter "_system_trig_enabled"=FALSE .
    But , I have a logon trigger . If I set this to FALSE , logon trigger does not kick in .
    How to have a logon trigger working and to avoid this error ?
    QL> drop table t;
    drop table t
    ORA-00604: error occurred at recursive SQL level 1
    ORA-01008: not all variables bound
    ORA-06512: at line 21
    SQL> alter system set "_system_trig_enabled"=FALSE;
    System altered
    SQL> drop table t;
    Table dropped

  • Default value? Trigger?

    Hi all,
    I got one Oracle 10g problem here, not sure you can help me or not.
    If a table has a column which has "default value" setup.
    Example
    CREATE TABLE KENTEMP
    refno number(10),
    user_create varchar2(30) Default USER not null
    And it also has a trigger with following contents:
    If :new.user_create is Null then
    :new.user_create := 'TEST';
    end if;
    If I going insert a record with null value on user_create column.
    In some Oracle database, the create_user will become USER, some will become "TEST".
    Do you understand why?
    Thanks

    In some Oracle database, the create_user will become USER, some will become "TEST". Are you running the same INSERT statement on all these databases? Because the default value gets applied before the trigger fires, and I would expect that to be consistent across all databases.
    SQL>  create table defval (col1 number, col2 varchar2(30) default user)
      2  /
    Table created.
    SQL> insert into defval (col1) values (1)
      2  /
    1 row created.
    SQL> select * from defval
      2  /
          COL1 COL2
             1 APC
    SQL> create trigger defval_trg before insert on defval for each row
      2  begin
      3    if :new.col2 is null then
      4       :new.col2 := 'TEST';
      5    end if;
      6  end;
      7  /
    Trigger created.
    SQL> insert into defval (col1) values (2)
      2  /
    1 row created.
    SQL> select * from defval
      2  /
          COL1 COL2
             1 APC
             2 APC
    SQL> insert into defval (col1,col2) values (3, null)
      2  /
    1 row created.
    SQL> select * from defval
      2  /
          COL1 COL2
             1 APC
             2 APC
             3 TEST
    SQL> Cheers, APC
    Blog : http://radiofreetooting.blogspot.com/

  • Help me write a trigger : I have no idea how to  :(

    Hi,
    I have to design a trigger based on the following requirement:
    I have an ASSET table ASSET (asset_id number(10) (primary key) , site_id (foreign key) references SITE(site_id) , cost_ctr_id (foreign key) references COST_CENTER(cost_ctr_id) )
    I have a COST_CENTER table COST_CENTER (cost_center_id number(10) primary key) I have a SITE table SITE (site_id number(10) primary key)
    I have a SITE_COST_CTR table SITE_COST_CTR (site_id (foreign key) references SITE(site_id ) , cost_ctr_id (foreign key) references COST_CENTER(cost_ctr_id) ) here (site_id, cost_ctr_id) is the composite primary key .
    Now I want a trigger which should satisfy the following : Whenever there is an insert or update in the ASSET table, it should first check in the SITE table and if the site_id is not there it should insert that site_id in the site table, similarly for cost_center_id it should see the cost center table and insert cost_center_id there, followed by an insert into SITE_COST_CTR table (It should insert site_id, cost_center_id in SITE_COST_CTR table)
    Can anyone please help me with this trigger ? I have no idea, never ever done it till date :'(. Please help me.
    Here's my effort so far, and I am not even a novice in this area!
    CREATE OR REPLACE TRIGGER TR_SITE_COST_CTR
    BEFORE INSERT OR UPDATE ON ASSET
    REFERENCING NEW AS NEW_ASSET
    FOR EACH ROW
    WHEN ( (SELECT COUNT(*) FROM SITE WHERE SITE_ID = NEW_ASSET.SITE_ID) > 1 AND (SELECT COUNT(*) FROM COST_CENTER WHERE COST_CENTER_ID = NEW_ASSET.COST_CENTER_ID) > 1 )
    BEGIN
    INSERT INTO SITE (SITE_ID) VALUES (:NEW_ASSET.SITE_ID);
    INSERT INTO COST_CENTER VALUES (:NEW_ASSET.COST_CENTER_ID , :NEW_ASSET.COST_CENTER_ID); INSERT INTO SITE_COST_CENTER VALUES (:NEW_ASSET.SITE_ID, :NEW_ASSET.COST_CENTER_ID);
    END
    Thanks in advance :)

    SQL> create table site (site_id number(10) primary key)
      2  /
    Tabel is aangemaakt.
    SQL> create table cost_center (cost_ctr_id number(10) primary key)
      2  /
    Tabel is aangemaakt.
    SQL> create table site_cost_ctr
      2  ( site_id     number(10) references site(site_id)
      3  , cost_ctr_id number(10) references cost_center(cost_ctr_id)
      4  , primary key (site_id,cost_ctr_id)
      5  )
      6  /
    Tabel is aangemaakt.
    SQL> create table asset
      2  ( asset_id    number(10) primary key
      3  , site_id     number(10) references site(site_id)
      4  , cost_ctr_id number(10) references cost_center(cost_ctr_id)
      5  )
      6  /
    Tabel is aangemaakt.
    SQL> create trigger tr_site_cost_ctr
      2  before insert or update on asset for each row
      3  declare
      4    l_dummy number;
      5  begin
      6    begin
      7      select site_id
      8        into l_dummy
      9        from site
    10       where site_id = :new.site_id
    11      ;
    12    exception
    13    when no_data_found then
    14      insert into site (site_id) values (:new.site_id);
    15    end
    16    ;
    17    begin
    18      select cost_ctr_id
    19        into l_dummy
    20        from cost_center
    21       where cost_ctr_id = :new.cost_ctr_id
    22      ;
    23    exception
    24    when no_data_found then
    25      insert into cost_center (cost_ctr_id) values (:new.cost_ctr_id);
    26    end
    27    ;
    28    begin
    29      select site_id
    30        into l_dummy
    31        from site_cost_ctr
    32       where site_id = :new.site_id
    33         and cost_ctr_id = :new.cost_ctr_id
    34      ;
    35    exception
    36    when no_data_found then
    37      insert into site_cost_ctr (site_id,cost_ctr_id) values (:new.site_id,:new.cost_ctr_id);
    38    end
    39    ;
    40  end;
    41  /
    Trigger is aangemaakt.
    SQL> insert into asset values (1, 11, 21)
      2  /
    1 rij is aangemaakt.
    SQL> insert into asset values (2, 11, 22)
      2  /
    1 rij is aangemaakt.
    SQL> insert into asset values (3, 12, 21)
      2  /
    1 rij is aangemaakt.
    SQL> insert into asset values (4, 11, 21)
      2  /
    1 rij is aangemaakt.
    SQL> select * from site
      2  /
                                   SITE_ID
                                        11
                                        12
    2 rijen zijn geselecteerd.
    SQL> select * from cost_center
      2  /
                               COST_CTR_ID
                                        21
                                        22
    2 rijen zijn geselecteerd.
    SQL> select * from site_cost_ctr
      2  /
                                   SITE_ID                            COST_CTR_ID
                                        11                                     21
                                        11                                     22
                                        12                                     21
    3 rijen zijn geselecteerd.
    SQL> select * from asset
      2  /
                                  ASSET_ID                                SITE_ID                            COST_CTR_ID
                                         1                                     11                                 21
                                         2                                     11                                 22
                                         3                                     12                                 21
                                         4                                     11                                 21
    4 rijen zijn geselecteerd.Regards,
    Rob.

  • What is wrong in this trigger

    Hello All,
    please tell me whats wrong in the following trigger,
    what effectively i am trying here is I wanted to insert the old records
    before update to a temporary table, if this is not the way, then what is the correct way.
    SQL> desc ttt1;
    Name Null? Type
    C1 NUMBER
    C2 NUMBER
    C3 NUMBER
    BMU_ID NUMBER
    SQL> desc temp_changes;
    Name Null? Type
    BMU_ID NUMBER
    C2 NUMBER
    C3 NUMBER
    SQL> ed
    Wrote file afiedt.buf
    1 create or replace trigger tri_ttt1
    2 before update of c3, c2 on ttt1 REFERENCING OLD AS old_ttt1 NEW AS new_ttt1
    3 begin
    4 insert into temp_changes
    5 SELECT BMU_ID,C2,C3
    6 FROM ttt1
    7 WHERE old_ttt1.c2<>new_ttt1.c2
    8 AND old_ttt1.C3<>new_ttt1.C3;
    9* end;
    SQL> /
    Warning: Trigger created with compilation errors.
    SQL> sho err
    Errors for TRIGGER TRI_TTT1:
    LINE/COL ERROR
    2/1 PL/SQL: SQL Statement ignored
    6/18 PL/SQL: ORA-00904: "NEW_TTT1"."C3": invalid identifier

    you forgot the colon (:) before new and old...

Maybe you are looking for

  • Stored Scripts are gone after upgrade from 1.5 to 2.0

    Upgraded from 1.5 to 2.0 and there are now problems with the "SQL Scripts" in SQL Workshop: 1. SQL scripts appear to have gone missing - over 200 from one workspace. I checked the WWV_FLOW_FILE_OBJECTS$ table in 2.0 and they are not in there. 2. All

  • Standard  Purchase Order XSL-FO

    Hi, I'm trying to insert the requestors telephone number into the standard po template in the 'Deliver To: ' area of the document. The requestor name and email address is already seeded but I'm having difficulty identifying what should be used for th

  • Updating a file using CIS API

    Hi, Is there any CIS API that lets you overwrite an existing file in the UCM. the idea is, not to checkin a new revision but to overwrite the exiting one. I looked at update API (ISCSDocumentUpdateAPI ) but it can only update the attributes of docume

  • Cannot find symbol class ParseException

    I have this in my code how ever DateFormat formatter = new SimpleDateFormat("ddMMyyyy"); dDateStamp = (Date)formatter.parse(dateStamp); When I pass in say dateStamp=safsadssad sa; I get an error which is fine. I can not seem to catch this error with

  • Mouse wrangling, can the mouse be confined to an area of a swf

    I want to be able to make the mouse only able to move around on part of the stage namely the bottom 75px. So I want ot to be able to move 100% on the X axis but I want to restrict the movement along the y axis. Is there a way to do this without using