How to create a stored procedure that contains all 3 AFTER Triggers Update/Insert/Delete ?

Hi guys, I'm trying to create a Stored procedure that will automatically add all 3 After triggers when executed on any given database, can someone please explain and give an example on how do I go about doing this ? I'd also like it to raise any errors
that may come across, thanks in advance.

Lets start with the question why do you need the triggers at all. Since SQL Server 2005 we can use an OUTPUT clause.
This code can be re-written in SQL Server 2005 using the OUTPUT clause like below:
create table itest ( i int identity not null primary key, j int not null unique )
create table #new ( i int not null, j int not null)
insert into itest (j)
output inserted.i, inserted.j into #new
select o.object_id from sys.objects as o
select * from #new
drop table #new, itest;
go
Now from this example, you can see the integration of OUTPUT clause with existing DML syntax.
Another common scenario is auditing of data in a table using triggers. In this case, the trigger uses information from the inserted and updated tables to add rows into the audit tables. The example below shows code that uses OUTPUT clause in UPDATE and DELETE
statements to insert rows into an audit table.
create table t ( i int not null );
create table t_audit ( old_i int not null, new_i int null );
insert into t (i) values( 1 );
insert into t (i) values( 2 );
update t
   set i  = i + 1
output deleted.i, inserted.i into t_audit
 where i = 1;
delete from t
output deleted.i, NULL into t_audit
 where i = 2;
select * from t;
select * from t_audit;
drop table t, t_audit;
go
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence

Similar Messages

  • How to create a stored procedure that accepts an array of args from Java?

    I am to be creating a stored procedure that accepts an array of arguments from Java. How to create this? thanks
    Sam

    Not a PL/SQL question really, but a Java one. The client call is done via ThinJDBC/OCI to PL/SQL, This call must be valid and match the parameters and data types of the PL/SQL procedure.
    E.g. Let's say I define the following array (collection) structure in Oracle:
    SQL> create or replace type TStrings as table of varchar2(4000);
    Then I use this as dynamic array input for a PL/SQL proc:
    create or replace procedure foo( string_array IN TStrings )...
    The client making the call to PL/SQL needs to ensure that it passes a proper TStrings array structure.. The Oracle Call Interface (OCI) supports this on the client side - allowing the client to construct an OCI variable that can be passed as a TStrings data type to SQL. Unsure just what JDBC supports in this regard.
    An alternative method, and a bit of a dirty hack, is to construct the array dynamically - but as this does not use bind variables, it is not a great idea.
    E.g. the client does the call as follows: begin
      foo( TStrings( 'Tom', 'Dick', 'Harry' ) );
    end;Where the TStrings constructor is created by the client by stringing together variables to create a dynamic SQL statement. A bind var call would look like this instead (and scale much better on the Oracle server side):begin
      foo( :MYSTRINGS );
    end;I'm pretty sure these concepts are covered in the Oracle Java Developer manuals...

  • How to create a stored procedure and use it in Crystal reports

    Hi All,
    Can anyone explain me how to create a stored procedure and use that stored procedure in Crystal reports. As I have few doubts in this process, It would be great if you can explain me with a small stored proc example.
    Thanks in advance.

    If you are using MSSQL SERVER then try creating a stored procedure like this
    create proc Name
    select * from Table
    by executing this in sql query analyzer will create a stored procedure that returns all the data from Table
    here is the syntax to create SP
    Syntax
    CREATE PROC [ EDURE ] procedure_name [ ; number ]
        [ { @parameter data_type }
            [ VARYING ] [ = default ] [ OUTPUT ]
        ] [ ,...n ]
    [ WITH
        { RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION } ]
    [ FOR REPLICATION ]
    AS sql_statement [ ...n ]
    Now Create new report and create new connection to your database and select stored procedure and add it to the report that shows all the columns and you can place the required fields in the report and refresh the report.
    Regards,
    Raghavendra
    Edited by: Raghavendra Gadhamsetty on Jun 11, 2009 1:45 AM

  • Can I create a Stored Procedure That access data from tables of another servers?

    I'm developing a procedure and within it I'm trying to access another server and make a select into a table that belongs to this another server. When I compile this procedure I have this error message: " PLS-00904: insufficient privilege to access object BC.CADPAP", where BC.CADPAP is the problematic table.
    How can I use more than one connection into an Oracle Stored Procedure?
    How I can access tables of a server from a Stored Procedure since the moment I'm already connected with another server?
    Can I create a Stored Procedure That access data from tables of another servers?

    You need to have a Database Link between two servers. Then you could do execute that statement without any problem. Try to create a database link with the help of
    CREATE DATABASE LINK command. Refer Document for further details

  • How to create java stored procedure from oracle(Dastageer)

    how to create java stored procedure from oracle-please help me to create the procedure.

    Hi,
    This forum is exclusively for discussions related to Sun Java Studio Creator. Please post your question in the appropriate forum.
    Thanks,
    RK.

  • How to Create a Stored Procedure

    Hi,
    how can we create a new stored procedure using a text editor and the saving it as a file. Please assume that i am just a beginner with oracle.

    You can create the stored procedure in a text editor, then run the saved file via SQL*Plus. If you have saved the file you can use the @ symbol to have Oracle run the script.
    c:\> sqlplus <<user name>>/<<password>>@<<TNS alias>>
    SQL> @<<path to file>>will start SQL*Plus and run the script you just created.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • How to call a stored procedure that use a type defined in a package?

    Hi all,
    this is stored procedure:
    GET_GIORNATAEVENTO( in_nome_servizio IN VARCHAR2,
    out_dati_aggiornati OUT TAB_VARCHAR2);
    TAB VARCHAR2 is defined in the package specification:
    TYPE tab_varchar2 IS TABLE OF VARCHAR2(5) INDEX BY BINARY_INTEGER;
    and this is the name of the package: PKG_SERVIZI_MMSPUSH.
    This is my php script:
    <?php
    // Connect to database...
    $c=OCILogon("venus_vfl", "venus_vfl", "venvi");
    if ( ! $c ) {
    echo "Connessione non riuscita: " . var_dump( OCIError() );
    die();
    echo "<br>PKG_SERVIZI_MMSPUSH.GET_GIORNATAEVENTO</br> ";
    echo "<br> </br>";
    // Call database procedure...
    $in_servizio = "MOTO";
    $s = OCIParse($c, "begin PKG_SERVIZI_MMSPUSH.GET_GIORNATAEVENTO(:bind1, :bind2); end;");
    OCIBindByName($s, ":bind1", $in_servizio);
    OCIBindByName($s, ":bind2", $out_esito);
    OCIExecute($s,OCI_DEFAULT);
    echo "OUT_DATI_AGGIORNATI= " . $out_esito;
    // Logoff from Oracle
    OCILogoff($c);
    ?>
    How to test stored procedure to get the output parameter?
    Thanks in advance.

    Thanks,
    but I need to test stored procedures that uses type defined in the package.
    e.g.
    if I have s.p.
    PROCEDURE get_risultati_squadra
    ( in_squadra IN VARCHAR2,
    out_serie OUT tab_varchar2_5,
    out_tiporisultato OUT tab_varchar2_5,
    out_n_giornata OUT tab_varchar2_5,
    out_squadre OUT tab_varchar2_200,
    out_risultato OUT tab_varchar2_10,
    out_marcatore OUT tab_varchar2_50,
    out_punti OUT tab_varchar2_3,
    out_rimbalzista OUT tab_varchar2_50,
    out_rimbalzi OUT tab_varchar2_3,
    out_esito OUT tab_varchar2_2);
    I have to define every type external to the package, in this case five new TYPE !!
    Is there another way to solve this problem?
    Thanks

  • How to call a stored procedure that has Table Of data types in VB6?

    Hi everyone,
    I need to call a stored procedure that has a Table Of data type as an input parameter (possibly even several Table Of input parameters). I can't seem to find any example of how to do this in VB6 using ODBC. Is this even possible?
    Thanks you!
    Steve

    Thanks,
    but I need to test stored procedures that uses type defined in the package.
    e.g.
    if I have s.p.
    PROCEDURE get_risultati_squadra
    ( in_squadra IN VARCHAR2,
    out_serie OUT tab_varchar2_5,
    out_tiporisultato OUT tab_varchar2_5,
    out_n_giornata OUT tab_varchar2_5,
    out_squadre OUT tab_varchar2_200,
    out_risultato OUT tab_varchar2_10,
    out_marcatore OUT tab_varchar2_50,
    out_punti OUT tab_varchar2_3,
    out_rimbalzista OUT tab_varchar2_50,
    out_rimbalzi OUT tab_varchar2_3,
    out_esito OUT tab_varchar2_2);
    I have to define every type external to the package, in this case five new TYPE !!
    Is there another way to solve this problem?
    Thanks

  • How to create a stored procedure in a dynamic schema

    Hi,
    I want to create a stored procedure in a dynamic shcema (schema name will be known at run time). Can any one guide me on this.
    I tried using define var1=schema1; and then in create or replace procedure &var1.porcName( ) but it is not working
    Thanks

    SQL> alter session set current_schema=<my schema>;
    Now create the stored procedure. It will be created in the session's current schema.

  • How to wrap a stored procedure that outputs PL/SQL records for JDBC?

    Hello everybody,
    Is there an example for wrapping a stored procedure that outputs PL/SQL records and/or PL/SQL tables of records, so that it can be called from JDBC?
    Since this is not possible with the Oracle JDBC driver, Oracle recommends "To wrap a stored procedure that uses PL/SQL tables, break the data into components or perhaps use Oracle collection types." (http://download-west.oracle.com/docs/cd/B12037_01/java.101/b10979/ref.htm#sthref2123)
    Many thanks for any help,
    Cheers, Christoph

    Hi Christoph,
    Have you tried using JPublisher, or -more easily- JDeveloper (Go to your database connection in the "Connections" pane, open the "Packages" node, right click to "Generate Java...").
    These approaches (at minimum, use of jpub) will generate required PL/SQL wrapper code, including SQL Type declarations. Once these are installed in the database, you can invoke the wrapper procedures directly from Java.
    -- Ekkehard

  • How to create minimal stored procedure?

    What is the preferred way of creating stored procedures? Can I use SQL Developer or SQLPlus?
    I'm running version 11.2.0.1.0.
    Here is my attempt in SQLDeveloper:
    CREATE OR REPLACE PROCEDURE hello ()
    BEGIN
    dbms_output.put_line('Hello, World!');
    END;
    SET SERVEROUTPUT ON;
    SELECT hello() from DUAL;
    When I hit F5 it says
    Warning: execution completed with warning
    PROCEDURE hello Compiled.
    When I select the last line and hit F9 I get a dialog box that says:
    An error was encountered performing the requested operation:
    ORA-00904: "HELLO" invalid identifier
    00904.0000 - "%s: invalid identifier"
    *Cause:
    *Action:
    Vendor code 904 Error at line:8 column 7
    I tried using SQL plus but since I'm having trouble just logging in, I already posted my query in the SQLPlus forum.
    Thanks,
    siegfried

    user8816970 wrote:
    What is the preferred way of creating stored procedures? Can I use SQL Developer or SQLPlus? Yes.
    A "minimal" procedure would be:
    create or replace procedure TestProc as
    begin
      null;
    end;Also get the whole pascalcase, camelcase and lowercase correct. Do not code in uppercase - it not only looks stupid, it contravenes programming standards that existed since the 70's and are still applicable and used today. From Microsoft's .Net to Java and /C/C++ and Pascal/Delphi and Visual Basic and most other languages. It is just plain silly to code in uppercase. Cobol standards do not apply today and were intended for punch cards - which is why I find this whole code-reserve-words-in-uppercase approach used in PL/SQL, flawed and idiotic.
    When I select the last line and hit F9 I get a dialog box that says:
    An error was encountered performing the requested operation:That is because PL/SQL procedures need to be executed via an anonymous PL./SQL block. You need use (enter) the following code block on the client side to be send to Oracle for parsing and execution:
    begin
      Hello;
    end;Some clients, like SQL*Plus, supports a client EXEC command. This takes the parameter supplied to the EXEC command and wrap that into an anonymous block like above.
    You can only execute PL/SQL functions via the SQL language. Quite important that you do not confuse languages at this level. Some clients (like SQL*Plus) have their own client commands like EXEC and HOST and SPOOL. These client commands are not PL/SQL or SQL.
    PL/SQL and SQL are also two different languages. PL/SQL combines Programming Language with SQL in a very integrated and transparent way. However. PL is executed by the PL engine and SQL is executed by the SQL engine.
    Lastly, make sure you understand what DBMS_OUTPUT does. It does not write anything to the client's display device. It is server code running in a server process. It cannot hack across the network to do stuff on the client - like reading a file or displaying something.
    The put_line() procedure of DBMS_OUTPUT writes text data into a static PL/SQL variable. The more you write into it, the more expensive server memory is consumed by that server process. When the server process has completed the client call (SQL statement or PL/SQL call), the client can then interrogate this buffer variable, read it, display the contents itself, and clear the buffer variable.
    It's important to understand what client-server is and how it applies to what you are doing using Oracle as a server.

  • How to Create a Stored Procedure in Oracle

    I try to create a very simple Stored Procedure from Oracle SQL Developer, got the following error. Can someone give me some help on this? I am new on this. Thanks.
    Error(4,1): PLS-00103: Encountered the symbol "BEGIN" when expecting one of the following: := ( ; not null range default character The symbol ";" was substituted for "BEGIN" to continue.
    create or replace PROCEDURE Test
    AS ACCESSTYP_ID ACCESSTYP.ACCESSTYPCD%TYPE
    BEGIN
         SELECT ACCESSTYPCD
         INTO ACCESSTYP_ID
         FROM ACCESSTYP
         WHERE ACCESSTYPCD = 'WWW';
    END;

    I found out I forgot to put ";" after the declare.
    How do I test it call this stored procedure from
    Oracle SQL Developer.
    create or replace PROCEDURE Test_VL
    AS ACCESSTYP_ID
    ACCESSTYP.ACCESSTYPCD%TYPE;
         SELECT ACCESSTYPCD
         INTO ACCESSTYP_ID
         FROM ACCESSTYP
         WHERE ACCESSTYPCD = 'WWW';
    END;in your SQL Developer window just enclosed your procedure with a Begin ... End.
      Begin
        Test_VL;
      End;

  • How to create an e-mail that contains a graphic flyer notice

    I need to create an e-mail poster advertisement for a
    recreation area that
    will be sent out to shareholders. I need to do this as an
    extra-curricular
    activity for work. Does anyone have any suggestions on how I
    would do this?
    Would I create the web page and then send the web page in an
    e-mail. I need
    the info to show up directly, not
    through an attachment. Also, once created, this will be sent
    out to
    shareholders. How do I save this file to disk( in what format
    )so that it
    can be sent out by my boss. Any suggestions would be helpful.
    Thanks
    jmick

    Thanks for your assistance. I went to mailchimp and found
    some helpful
    information. I also found another program and created a
    presentable draft
    that I have forwarded on. Thanks again.
    jmick

  • How do I create a smart album that contains all pictures with no keywords?

    Hi,
    I have many pictures which currently don't have any keywords at all. Now I want to tag these pictures with keywords. How can I create a smart album for those pictures without any keywords? So that I can then work just on these pictures...
    Note that I don't want to find pictures that don't have a specific keyword. I want to find all those pictures which have none keyword at all.
    Thanks,
    Rainer

    Well, there's a way but it's not great...
    Start with a smart album at whatever level you want to keyword everything under. Set to search where "rating is greater than or equal to unrated".
    Select all images, and apply a keyword like "NeedsKeyword". Yes, even the one with keywords already.
    Now change the smart folder - use the "+" menu on the upper right corner of the query box to add an "IPTC" search. In that row use the dropdown by IPTC to find "keywords", then set the one next to it to "is", then type "NeedsKeyword" (or whatever you used) into the text box. Now go up to the top of the query box and change the "Match" dropdown to be "all" instead of "Any".
    What we've done here is find all images where the only keyword is "NeedsKeyword", all the ones you've done with keywords already will not appear.
    Now, copy these images into an Album (not smart album) for tagging - this is because as soon as you tag an image it will vanish and you may wish to apply more than one tags).
    After you are done tagging, you want to remove the tag - this is trickier than you might think, as you need to remove it from images tagged before in addition to the images in the Album you just made.
    First, change your smart folder to once again find all images by unchecking the IPTC keyword search. Now you'll see all images - but you're not done yet! You cannot batch undo a keyword in a smart folder, even though you can batch add. Select all of the images and drag into the Album you were using to keyword. Inside an Album the keyword metadata inspector shows only common keywords, NeedsKeyword should be one of them - remove it and it will be gone, and all your images tagged. Now you can remove the Album and the Smart Album you created.
    Harder than it needs to be, I'd say - I've submitted feedback you need some way to search for untagged images. Heck, it may already be in 1.1! Or Joe might know of an easier way that has eluded me.
    Good luck!

  • Stored Procedure that creates a trigger on new tables

    I am trying to create a stored procedure that creates a trigger on new tables whenever the table is created.  The procedure should receive the new project table's name, and then create a dml trigger on that procedure.  When the procedure
    is run, I get an error "Incorrect syntax near keyword 'TRIGGER.'"  This is how my Stored Procedure looks in SQL Management Studio.  Any suggestions?
    USE [RIDB_DynamicDesign]
    GO
    /****** Object: StoredProcedure [dbo].[sp_CreateTriggerMarkLatest] Script Date: 11/08/2014 16:43:20 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [dbo].[sp_CreateTriggerMarkLatest] @ProjectTable nvarchar(128), @ItExists int OUTPUT
    AS
    DECLARE @SQL nvarchar(4000)
    DECLARE @MarkLatest nvarchar(30)
    DECLARE @LatTrue bit
    DECLARE @LatFalse bit
    SET @LatTrue = 'True'
    SET @LatFalse = 'False'
    SET @SQL = 'CREATE TRIGGER tr_MarkLatest ON ' + @ProjectTable + ' AFTER INSERT
    AS
    UPDATE ' + @ProjectTable + ' SET Latest = @LatFalse
    UPDATE ' + @ProjectTable + ' SET Latest = @LatTrue WHERE
    ID IN (SELECT ID FROM ' + @ProjectTable + ' p WHERE
    NOT EXISTS (SELECT 1 FROM ' + @ProjectTable + ' WHERE
    Name = p.Name AND Vers = p.Vers
    AND Date > p.Date))'
    EXEC sp_executesql @SQL, N'@ProjectTable nvarchar(128), @LatTrue bit, @LatFalse bit',
    @ProjectTable, @LatTrue, @LatFalse
    Gina

    First you have to debug the dynamic SQL string with a PRINT statement. I see some problems:
    CREATE PROCEDURE [dbo].[uspCreateTriggerMarkLatest] @ProjectTable nvarchar(128), @ItExists int OUTPUT
    AS BEGIN
    DECLARE @SQL nvarchar(4000)
    DECLARE @MarkLatest nvarchar(30)
    DECLARE @LatTrue bit
    DECLARE @LatFalse bit
    SET @LatTrue = 'True'
    SET @LatFalse = 'False'
    SET @SQL = 'CREATE TRIGGER tr_MarkLatest ON ' + @ProjectTable + ' AFTER INSERT
    AS
    UPDATE ' + @ProjectTable + ' SET Latest = @LatFalse
    UPDATE ' + @ProjectTable + ' SET Latest = @LatTrue WHERE
    ID IN (SELECT ID FROM ' + @ProjectTable + ' p WHERE
    NOT EXISTS (SELECT 1 FROM ' + @ProjectTable + ' WHERE
    Name = p.Name AND Vers = p.Vers
    AND Date > p.Date))'
    PRINT @SQL;
    -- EXEC sp_executesql @SQL, N'@ProjectTable nvarchar(128), @LatTrue bit, @LatFalse bit', @ProjectTable, @LatTrue, @LatFalse
    END
    GO
    DECLARE @ItExists int, @ProjectTable nvarchar(128) = N'TestTrigger';
    EXEC [dbo].[uspCreateTriggerMarkLatest] @ProjectTable, @ItExists OUTPUT
    CREATE TRIGGER tr_MarkLatest ON TestTrigger AFTER INSERT
    AS
    UPDATE TestTrigger SET Latest = @LatFalse
    UPDATE TestTrigger SET Latest = @LatTrue WHERE
    ID IN (SELECT ID FROM TestTrigger p WHERE
    NOT EXISTS (SELECT 1 FROM TestTrigger WHERE
    Name = p.Name AND Vers = p.Vers
    AND Date > p.Date))
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

Maybe you are looking for

  • This.submitForm() -- problem with my cgi script

    Thanks to George Johnson for an earlier answer to a related issue with this.submitForm. I am trying to use this.submitForm as per Example 1 on p. 348 of "JavaScript for Acrobat API Reference" document. To avoid any restrictions with my web hosting se

  • Bought Quicktime Pro and my computer died, do I have to buy it again?

    I bought Quicktime Pro back in 2006, recently my laptop died and I had to get it a new harddrive. I still have the serial number cause I bought it online. But it says it's an invalid number and I can't use it. Do I have to buy it again? Thank you!

  • Loop at where not in

    can anybody send me example of NOT IN with loop at  itab where  filed not in (a, ,b, c ) when i use brackets becomes red..i  dont know why

  • Safari Doesn't Recognize Symantec VIP Plugin

    Our company uses Symantec VIP for authentication.  I've just installed a fresh instance of Mac OS Mavericks and setting things up.  I've tried to install the Symantec plugin, but Safari doesn't recognize it.  It continually asks me to reinstall, but

  • Mouse behaving uncontrollable in Photoshop

    I had a weird problem pop up suddenly in Photoshop only. When I try to use a tool such as clone or brush- the curser jumps around uncontrollably? Earlier, I changed the aspect ratio of a file to square, and I also cannot seem to reset it. Are these t