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
Similar Messages
-
APEX fails with Java stored procedure that creates a JDBC connection
Hello!
We are facing a strange problem since we have upgraded from Oracle 10g and Apache to Oracle 11g with Embedded Gateway.
Here is what we do:
** APEXX calls a PL/SQL package function "OPEN_CONNECTION" that wraps a Java stored procedure called "openConnection".*
FILE_READER_REMOTE_API.openConnection(user, password, host, port, service);
** The Java stored procedures "openConnection" opens a JDBC connection to an other database:*
public class FileReaderRemote {
private static Connection conn = null;
private static DefaultContext remoteContext = null;
public static void openConnection(String user, String password, String host, String port, String service) throws SQLException {
// Load the Oracle JDBC driver
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
java.util.Properties props = new java.util.Properties();
props.put ("user", user);
props.put ("password", password);
//props.put ("database", "//" + host + ":" + port + "/" + service);
props.put ("database", host + ":" + port + ":" + service);
props.put("v$session.program", "FileReaderRemote2");
// Connect to the database
remoteContext = Oracle.getConnection("jdbc:oracle:thin:", props);
This procedure used to work fine before the upgrade, but now we see the following:
* It still works when called directly from TOAD or SQL*Plus, even under the user ANONYMOUS.
* When called from APEX and the target database is Oracle 11g, it still works.
* When called from APEX and the target database is Oracle 10g, it takes several minutes and we receive this error:
*"Socket read timed out"*
We have tested the following workaround:
We have created a database link to our own database and called the stored procedure through that database link.
FILE_READER_REMOTE_API.openConnection*@loopback*(user, password, host, port, service);
This works, but is not really an option.
I hope some one of you can explain this strange behaviour to me.
Best regards,
MatthiasYou wrote
"Java stored procedures -- by definition - are stored in the 8i rdbms. !!"
From the Oracle8i Java Stored Procedures Developer's Guide
Release 8.1.5
A64686-01
"If you create Java class files on the client side, you can use loadjava to upload them into the RDBMS. Alternatively, you can upload Java source files and let the Aurora JVM compile them. In most cases, it is best to compile and debug programs on the client side, then upload the class files for final testing within the RDBMS"
This means that you can create shared classes that are used on both the client and server side. The source does not need to reside within the server (according to their documentation). Please also note the following from the Oracle8i JDBC Developer's Guide and Reference Release 8.1.5 A64685-01 for using the getConnection() method on the server:
"If you connect to the database with the DriverManager.getConnection() method, then use the connect string jdbc:oracle:kprb:. For example:
DriverManager.getConnection("jdbc:oracle:kprb:");
Note that you could include a user name and password in the string, but because you are connecting from the server, they would be ignored."
So if you're coding a shared class that is to run on both the client and server side, you might do something like this:
Connection conn =
DriverManager.getConnection(
System.getProperty("oracle.server.version") == null
? "jdbc:oracle:thin:@hostname:1521:ORCL"
: "jdbc:oracle:kprb:"),
"youruserid","yourpassword");
As stated earlier, the userid and password are supposedly ignored for server connections retrieved in this manner. I haven't tried this yet, but it is documented by Oracle.
Regards,
Steve
null -
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 -
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 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
SamNot 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... -
Call Stored Procedure inside a db trigger
Is that possible to call stored procedure inside a db trigger ?
I User this code:
Create Or Replace Trigger Sale.Send_Auto_Email_Trg
After Insert
On Sale.Sale_Technical_Support
--Referencing New As New Old As Old
For Each Row
Declare
Pragma Autonomous_Transaction;
vn_count Number := 0;
vn_msg Number;
vv_exec Varchar2(5000);
Begin
If Inserting And :New.Ticket_Status = 2 Then
Begin
Begin
Select Count(*)
Into vn_count
From Sale_Technical_Support
Where Sending_Flag = 1
And Support_Type = 2;
Exception When No_Data_Found Then
vn_count := 0;
End;
If vn_count >= 1 And :New.Problem_Desc Is Not Null Then
Technical_Support_Mailing('[email protected]', -- To
'[email protected]',
'[email protected]', -- Bcc
'[email protected]', -- From
'رموز وصلاحيات',
2);
End If;
End;
End If;
End;
/No errors but the procedure doesn't executed !!!!!1) If you are using autonomous transactions for anything other that writing log data that you want to preserve even if the triggering transaction fails, you're probably doing something wrong. There is no reason to use an autonomous transaction here.
2) You don't want to send email from a trigger. You don't want to do anything non-transactional in a trigger. Oracle will, for example, rollback and re-execute parts of a statement for write consistency. If you send email in a trigger, you may get multiple emails for a single update. You may also get emails for updates that were never committed. And if the email server happens to be down, your transactions will fail.
3) If you use an autonomous transaction, the trigger will have a completely different transaction context from the parent. So when you query the table within the trigger, you won't be able to see any of the uncommitted changes including the changes that caused the trigger to fire. My guess is that you are assuming that the row that you inserted is visible to the trigger.
Justin -
Error executing Stored Procedure that returns a recordset in Visual Basic 6
Hello, i tried to use the example in the link posted as a response to my question in a previous thread, and in Visual Basic 6, when i execute the Stored procedure it gives me the following error:
This is the package created as indicated in the example FAQ you posted.
package types
as
type cursorType is ref cursor;
end;
This is the procedure created as indicated in the example FAQ you posted.
PROCEDURE SP_TITUVALO(T_BR IN VARCHAR2,
P_Cursor OUT TYPES.cursorType )
AS
BEGIN
OPEN P_Cursor FOR
SELECT * FROM TASAS WHERE BR=T_BR AND TASA > 0;
END;
This is the code used to execute the Stored Procedure in VB6:
Dim objConn As New ADODB.Connection
Dim connString
Dim cmdStoredProc As New ADODB.Command
Dim param1 As New ADODB.Parameter
Dim RS As ADODB.Recordset
Set param1 = cmdStoredProc.CreateParameter("T_BR", adVarChar, adParamInput, 255, "97")
cmdStoredProc.Parameters.Append param1
objConn.Open strconex
Set cmdStoredProc.ActiveConnection = objConn
cmdStoredProc.CommandText = "SP_TITUVALO"
cmdStoredProc.CommandType = adCmdStoredProc
Set RS = cmdStoredProc.Execute
This is the error returned:
ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'SP_TITUVALO'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
****************************************************************Juan,
Not sure about FAQ you are referring to, but it seems that you need to set PLSQLRSet property of ADODB.Command to TRUE. Because if you fail to do so - errors with refcursors are likely to happen.
Consider:
Set objConn = CreateObject("ADODB.Connection")
objConn.ConnectionString = "Provider=OraOLEDB.Oracle;Persist Security Info=False;Data Source=test9ora;User ID=max;Password=blabla"
objConn.Open
'Dim cmdStoredProc
Set cmdStoredProc = CreateObject("ADODB.Command")
Dim param1
Set param1 = cmdStoredProc.CreateParameter("T_BR", adVarChar, adParamInput, 255, "97")
param1.Value = "X"
cmdStoredProc.Parameters.Append param1
'Dim RS
Set cmdStoredProc.ActiveConnection = objConn
'The following line was missed out
cmdStoredProc.Properties("PLSQLRSet") = True
cmdStoredProc.CommandText = "SP_TITUVALO"
cmdStoredProc.CommandType = adCmdStoredProc
Set RS = cmdStoredProc.ExecuteThis works fine, at least for me.
Cheers. -
Call to Oracle stored procedure that returns ref cursor doesn't work
I'm trying to use an OData service operation with Entity Framework to call an Oracle stored procedure that takes an number as an input parameter and returns a ref cursor. The client is javascript so I'm using the rest console to test my endpoints. I have been able to successful call a regular Oracle stored procedure that takes a number parameter but doesn't return anything so I think I have the different component interactions correct. When I try calling the proc that has an ref cursor for the output I get the following an error "Invalid number or type of parameters". Here are my specifics:
App.config
<oracle.dataaccess.client>
<settings>
<add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursor.P_RESULTS" value="implicitRefCursor bindinfo='mode=Output'" />
<add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.0" value="implicitRefCursor metadata='ColumnName=WINDFARM_ID;BaseColumnName=WINDFARM_ID;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Number;ProviderType=Int32'" />
<add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.1" value="implicitRefCursor metadata='ColumnName=STARTTIME;BaseColumnName=STARTTIME;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Varchar2;ProviderType=Varchar2'" />
<add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.2" value="implicitRefCursor metadata='ColumnName=ENDTIME;BaseColumnName=ENDTIME;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Varchar2;ProviderType=Varchar2'" />
<add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.3" value="implicitRefCursor metadata='ColumnName=TURBINE_NUMBER;BaseColumnName=TURBINE_NUMBER;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Varchar2;ProviderType=Varchar2'" />
<add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.4" value="implicitRefCursor metadata='ColumnName=NOTES;BaseColumnName=NOTES;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Varchar2;ProviderType=Varchar2'" />
<add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.5" value="implicitRefCursor metadata='ColumnName=TECHNICIAN_NAME;BaseColumnName=TECHNICIAN_NAME;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Varchar2;ProviderType=Varchar2'" />
<add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYID.RefCursor.P_RESULTS" value="implicitRefCursor bindinfo='mode=Output'" />
</settings>
OData Service Operation:
public class OracleODataService : DataService<OracleEntities>
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("GetWorkOrdersByWindfarmId", ServiceOperationRights.All);
config.SetServiceOperationAccessRule("CreateWorkOrder", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
[WebGet]
public IQueryable<GetWorkOrdersByWindfarmId_Result> GetWorkOrdersByWindfarmId(int WindfarmId)
return this.CurrentDataSource.GetWorkOrdersByWindfarmId(WindfarmId).AsQueryable();
[WebGet]
public void CreateWorkOrder(int WindfarmId)
this.CurrentDataSource.CreateWorkOrder(WindfarmId);
Here is the stored procedure:
procedure GetWorkOrdersByWindFarmId(WINDFARMID IN NUMBER,
P_RESULTS OUT REF_CUR) is
begin
OPEN P_RESULTS FOR
select WINDFARM_ID,
STARTTIME,
ENDTIME,
TURBINE_NUMBER,
NOTES,
TECHNICIAN_NAME
from WORKORDERS
where WINDFARM_ID = WINDFARMID;
end GetWorkOrdersByWindFarmId;
I defined a function import for the stored procedure using the directions I found online by creating a new complex type. I don't know if I should be defining the input parameter, WindfarmId, in my app.config? If I should what would that format look like? I also don't know if I'm invoking the stored procedure correctly in my service operation? I'm testing everything through the rest console because the client consuming this information is written in javascript and expecting a json format. Any help is appreciated!
Edited by: 1001323 on Apr 20, 2013 8:04 AM
Edited by: jennyh on Apr 22, 2013 9:00 AMMaking the change you suggested still resulted in the same Oracle.DataAccess.Client.OracleException {"ORA-06550: line 1, column 8:\nPLS-00306: wrong number or types of arguments in call to 'GETWORKORDERSBYWINDFARMID'\nORA-06550: line 1, column 8:\nPL/SQL: Statement ignored"} System.Exception {Oracle.DataAccess.Client.OracleException}
I keep thinking it has to do with my oracle.dataaccess.client settings in App.Config because I don't actually put the WindfarmId and an input parameter. I tried a few different ways to do this but can't find the correct format. -
Stored procedure that returns multiple tables
Hello everyone,
I was wondering if there's a way to write a stored procedure that returns multiple result set as in sql server. for example, in sql server, you can write 2 select statements and when loading them in c#, u can get two data tables.
I am not sure having a single ref cursor for each select is the only solution. I might need to return a variable number of tables per procedure call (based on a certain criteria).
Any ideas?
thanks for your timeSure. Ref cursor is the only easier answer for your problem.
satyaki>
satyaki>select * from v$version;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
Elapsed: 00:00:01.43
satyaki>
satyaki>create or replace procedure ref_gen_arg(choice in int,b in out sys_refcursor)
2 is
3 str varchar2(500);
4 begin
5 if choice = 1 then
6 str := 'select * from emp';
7 elsif choice = 2 then
8 str := 'select * from dept';
9 end if;
10
11 open b for str;
12 exception
13 when others then
14 dbms_output.put_line(sqlerrm);
15 end;
16 /
Procedure created.
Elapsed: 00:00:04.38
satyaki>
satyaki>
satyaki>declare
2 rec_x emp%rowtype;
3 rec_y dept%rowtype;
4 w sys_refcursor;
5 begin
6 dbms_output.enable(1000000);
7 ref_gen_arg(1,w);
8 loop
9 fetch w into rec_x;
10 exit when w%notfound;
11 dbms_output.put_line('Employee No: '||rec_x.empno||' - '||
12 'Name: '||rec_x.ename||' - '||
13 'Job: '||rec_x.job||' - '||
14 'Manager: '||rec_x.mgr||' - '||
15 'Joining Date: '||rec_x.hiredate||' - '||
16 'Salary: '||rec_x.sal||' - '||
17 'Commission: '||rec_x.comm||' - '||
18 'Department No: '||rec_x.deptno);
19 end loop;
20 close w;
21
22 ref_gen_arg(2,w);
23 loop
24 fetch w into rec_y;
25 exit when w%notfound;
26 dbms_output.put_line('Department No: '||rec_y.deptno||' - '||
27 'Name: '||rec_y.dname||' - '||
28 'Location: '||rec_y.loc);
29 end loop;
30 close w;
31 exception
32 when others then
33 dbms_output.put_line(sqlerrm);
34 end;
35 /
Employee No: 9999 - Name: SATYAKI - Job: SLS - Manager: 7698 - Joining Date: 02-NOV-08 - Salary: 55000 - Commission: 3455 - Department No: 10
Employee No: 7777 - Name: SOURAV - Job: SLS - Manager: - Joining Date: 14-SEP-08 - Salary: 45000 - Commission: 3400 - Department No: 10
Employee No: 7521 - Name: WARD - Job: SALESMAN - Manager: 7698 - Joining Date: 22-FEB-81 - Salary: 1250 - Commission: 500 - Department No: 30
Employee No: 7566 - Name: JONES - Job: MANAGER - Manager: 7839 - Joining Date: 02-APR-81 - Salary: 2975 - Commission: - Department No: 20
Employee No: 7654 - Name: MARTIN - Job: SALESMAN - Manager: 7698 - Joining Date: 28-SEP-81 - Salary: 1250 - Commission: 1400 - Department No: 30
Employee No: 7698 - Name: BLAKE - Job: MANAGER - Manager: 7839 - Joining Date: 01-MAY-81 - Salary: 2850 - Commission: - Department No: 30
Employee No: 7782 - Name: CLARK - Job: MANAGER - Manager: 7839 - Joining Date: 09-JUN-81 - Salary: 4450 - Commission: - Department No: 10
Employee No: 7788 - Name: SCOTT - Job: ANALYST - Manager: 7566 - Joining Date: 19-APR-87 - Salary: 3000 - Commission: - Department No: 20
Employee No: 7839 - Name: KING - Job: PRESIDENT - Manager: - Joining Date: 17-NOV-81 - Salary: 7000 - Commission: - Department No: 10
Employee No: 7844 - Name: TURNER - Job: SALESMAN - Manager: 7698 - Joining Date: 08-SEP-81 - Salary: 1500 - Commission: 0 - Department No: 30
Employee No: 7876 - Name: ADAMS - Job: CLERK - Manager: 7788 - Joining Date: 23-MAY-87 - Salary: 1100 - Commission: - Department No: 20
Employee No: 7900 - Name: JAMES - Job: CLERK - Manager: 7698 - Joining Date: 03-DEC-81 - Salary: 950 - Commission: - Department No: 30
Employee No: 7902 - Name: FORD - Job: ANALYST - Manager: 7566 - Joining Date: 03-DEC-81 - Salary: 3000 - Commission: - Department No: 20
Department No: 10 - Name: ACCOUNTING - Location: NEW YORK
Department No: 20 - Name: RESEARCH - Location: DALLAS
Department No: 30 - Name: SALES - Location: CHICAGO
Department No: 40 - Name: LOGISTICS - Location: CHICAGO
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.73
satyaki>Regards.
Satyaki De. -
I have a stored procedure that dynamically creates a pivot query. The procedure works and returns the correct data. Now I have a requirement to show this data in reporting system that can only pull from a table or view. Since you can not
create a dynamic query in a view I tried to do a select from using openquery.
Example 'Select * from OpenQuery([MyServername], 'Exec Instance.Schema.StoredProcedure')
I get the error back "the linked server indicates the object has no columns". I assume this is because of the first select statement that is stuffing the variable with column names.
CODE FROM PROCEDURE
Alter PROCEDURE [dbo].[Procedure1]
AS
BEGIN
SET NOCOUNT ON
Declare @cols nvarchar(2000),
@Tcols nvarchar(2000),
@Sql nvarchar (max)
select @cols = stuff ((
Select distinct '], ['+ModelName + ' ' + CombustorName
from CombustorFuel cf
join Model m on cf.modelid = m.modelid
join Combustors cb on cf.CombustorID = cb.CombustorID
where cf.CombustorID > 0
for XML Path('')
),1,2,'')+']'
Set @Tcols = replace(@Cols, ']', '] int')
--Print @Tcols
--Print @Cols
Set @Sql = 'Select GasLiquid, FuelType, '+ @Cols +'
from
Select GasLiquid, FuelType, ModelName+ '' '' +CombustorName ModelCombustor, CombFuelStatus+''- ''+CombFuelNote CombFuelStatusNote
from Frames f
join Family fa on f.Frameid = fa.frameid
join Model m on fa.FamilyID = m.FamilyID
join CombustorFuel cf on m.Modelid = cf.modelid
Join Combustors c on cf.CombustorId = c.CombustorID
join FuelTypes ft on cf.FuelTypeID = ft.FuelTypeID
where cf.CombustorFuelID > 0
and CombustorName <> ''''
) up
Pivot
(max(CombFuelStatusNote) for ModelCombustor in ('+ @Cols +')) as pvt
order by FuelType'
exec (@Sql)Then again, a good reporting tool should be able to do dynamic pivot on its own, because dynamic pivoting is a presentation feature.
SSRS Supports dynamic columns: Displaying Dynamic Columns in SSRS Report
SQL Reporting Services with Dynamic Column Reports
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014
Displaying and reading are two very different things.
#1) SSRS Needs a fixed field list on the input side to know what what to make available in the designer.
#2) SSRS cant read "exec (@Sql)" out of a proc, even if there is a fixed number of columns (at
least it can't use it to auto build the field list from the proc)
I use dynamic SQL in my report procs on a fairly regular basis and I've found it easiest to simply dump
the results of my dynamic sql into a temp table at the end of the procs and then select from the temp table.
Basically, Erland is correct. Stop trying to pivot in the query and let SSRS (or whatever reporting software you're using) handle it with a Martix.
Jason Long -
How to execute stored procedure that returns a cursor?
How to execute a stored procedure that returns a cursor?
Follow the code:
CREATE OR REPLACE PROCEDURE stp_cashin_grupo
(p_func IN VARCHAR
,p_cod_grup IN Integer
,p_des_grup IN VARCHAR
,p_logi IN VARCHAR
,p_curs_rset OUT infoc.pck_cashin_grupo.curs_rset
IS
BEGIN
if p_func = '1' then
OPEN p_curs_rset FOR
select
cod_grup
,des_grup
,dat_manu_grup
,des_logi_manu
from infoc.tbl_cashin_grupo
order by des_grup;
end if;
END stp_cashin_grupo;
and the package:
CREATE OR REPLACE PACKAGE pck_cashin_grupo
AS
TYPE curs_rset IS REF CURSOR;
END pck_cashin_grupo;
My question is how to execute in sql plus?
EXEC stp_cashin_grupo('1',0,'','465990', my doubt is how to pass the cursor as return
Thanksmy doubt is how to pass the cursor as returnExample :
TEST@db102 > var c1 refcursor;
TEST@db102 > create or replace procedure ref1 (
2 v1 in varchar2,
3 cur1 out sys_refcursor)
4 is
5 begin
6 open cur1 for 'select * from '||v1;
7 end;
8 /
Procedure created.
TEST@db102 > exec ref1('dept',:c1);
PL/SQL procedure successfully completed.
TEST@db102 > print c1
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
TEST@db102 > -
Ssrs 2008 r2 pass mutiple values to stored procedure that is being called
In an SSRS 2008 r2 report, I am currently calling a stored procedure called spRoom. I obtain the results of the stored procedure by creating a temptable called #roomReults
The temp table that I am creating and using to obtain results looks like the following:
CREATE TABLE #roomResults(
studentID VARCHAR(15),
endYear SMALLINT,
calendarID INT)
INSERT #roomResults
EXEC [dbo].[spRoom] @endYear, @calendarID
Currently I am only passing in one value for both paramters called: @endYear and @calendarID. However now I want to pass
in several values to each parameter.
I want to change the sql to look like the following:
EXEC [dbo].[spRoom] IN (@endYear), In (@calendarID)
The above gives me syntax errors.
Thus I am wondering if you can show me how to change the sql listed above so that that I can pass in more than one value from the SSRS report parameters called @endYear and @calendarID to the stored procedure called [spRoom]?Wendy
What version are you using? Since SQL Server 2008 we can use table valued parameter
Create a user-defined data type with a single column.
Develop a procedure with a table variable as an input parameter.
Declare a table variable of the type of the user defined data type.
Loading 10 records into the table variable and pass the table
variable to the stored procedure.
create type tt_example AS TABLE
(spid int)
go
create procedure usp_example
@spids tt_example READONLY
AS
SELECT *
FROM @spids
GO
declare @spids tt_example
insert into @spids
select top 10 spid
from sys.sysprocesses
exec usp_example @spids=@spids
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 -
Calling of Stored Procedure in After Insert Trigger
Can I call a Stored Procedure in After Insert Trigger ?
Please send a sample code (good example) of After Insert Trigger.
Thanks.Kishore,
I have two table WLCS_ORDER, WLCS_ORDER_LINE
WLCS_ORDER - It holds order header information like
ORDER_ID
CUSTOMER_ID
TRANSACTION_ID
STATUS
ORDER_DATE
SHIPPING_METHOD
SHIPPING_AMOUNT
SHIPPING_CURRENCY
PRICE_AMOUNT
PRICE_CURRENCY
SHIPPING_GEOCODE
SHIPPING_STREET1
SHIPPING_STREET2
SHIPPING_CITY
SHIPPING_STATE
SHIPPING_COUNTRY
SHIPPING_POBOX
SHIPPING_COUNTY
SHIPPING_POSTAL_CODE
SHIPPING_POSTAL_CODE_TYPE
SPECIAL_INSTRUCTIONS
SPLITTING_PREFERENCE
ORDER_SUBTOTAL
WLCS_ORDER_LINE - It holds all order lines information like
ORDER_LINE_ID
QUANTITY
PRODUCT_ID
TAX_AMOUNT
TAX_CURRENCY
SHIPPING_AMOUNT
SHIPPING_CURRENCY
UNIT_PRICE_AMOUNT
UNIT_PRICE_CURRENCY
MSRP_AMOUNT
MSRP_CURRENCY
DESCRIPTION
ORDER_ID
TOTAL_LINE_AMOUNT
Relation between WLCS_ORDER, WLCS_ORDER_LINE is one to many.
For each WLCS_ORDER row, one or more order lines will insert into WLCS_ORDER_LINE table.
For each new row in WLCS_ORDER table, I have to update the following columns in both the tables with my maths.
WLCS_ORDER
shipping_amount
price_amount
order_subtotal
WLCS_ORDER_LINE
shipping_amount
I thought I can do this in after insert trigger, But if it is not possible, Please give the best way to fulfill this requirement.
I appreciate your help.
Have a great day.
Srinivas -
Invoking stored procedure that returns array(oracle object type) as output
Hi,
We have stored procedures which returns arrays(oracle type) as an output, can anyone shed some light on how to map those arrays using JPA annotations? I tried using jdbcTypeName but i was getting wrong type or argument error, your help is very much appreciated. Below is the code snippet.
JPA Class:
import java.io.Serializable;
import java.sql.Array;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.eclipse.persistence.annotations.Direction;
import org.eclipse.persistence.annotations.NamedStoredProcedureQuery;
import org.eclipse.persistence.annotations.StoredProcedureParameter;
* The persistent class for the MessagePublish database table.
@Entity
@NamedStoredProcedureQuery(name="GetTeamMembersDetails",
procedureName="team_emp_maintenance_pkg.get_user_team_roles",
resultClass=TeamMembersDetails.class,
returnsResultSet=true,
parameters={
@StoredProcedureParameter(queryParameter="userId",name="I_USER_ID",direction=Direction.IN,type=Long.class),
@StoredProcedureParameter(queryParameter="employeeId",name="I_EMPLOYEEID",direction=Direction.IN,type=Long.class),
@StoredProcedureParameter(queryParameter="TEAMMEMBERSDETAILSOT",name="O_TEAM_ROLES",direction=Direction.OUT,jdbcTypeName="OBJ_TEAM_ROLES"),
@StoredProcedureParameter(queryParameter="debugMode",name="I_DEBUGMODE",direction=Direction.IN,type=Long.class)
public class TeamMembersDetails implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private long userId;
private List<TeamMembersDetailsOT> teamMembersDetailsOT;
public void setTeamMembersDetailsOT(List<TeamMembersDetailsOT> teamMembersDetailsOT) {
this.teamMembersDetailsOT = teamMembersDetailsOT;
public List<TeamMembersDetailsOT> getTeamMembersDetailsOT() {
return teamMembersDetailsOT;
Procedure
PROCEDURE get_user_team_roles (
i_user_id IN ue_user.user_id%TYPE
, o_team_roles OUT OBJ_TEAM_ROLES_ARRAY
, i_debugmode IN NUMBER :=0)
AS
OBJ_TEAM_ROLES_ARRAY contains create or replace TYPE OBJ_TEAM_ROLES_ARRAY AS TABLE OF OBJ_TEAM_ROLES;
TeamMembersDetailsOT contains the same attributes defined in the OBJ_TEAM_ROLES.A few things.
You are not using a JDBC Array type in your procedure, you are using a PLSQL TABLE type. An Array type would be a VARRAY in Oracle. EclipseLink supports both VARRAY and TABLE types, but TABLE types are more complex as Oracle JDBC does not support them, they must be wrapped in a corresponding VARRAY type. I assume your OBJ_TEAM_ROLES is also not an OBJECT TYPE but a PLSQL RECORD type, this has the same issue.
Your procedure does not return a result set, so "returnsResultSet=true" should be "returnsResultSet=false".
In general I would recommend you change your stored procedure to just return a select from a table using an OUT CURSOR, that is the easiest way to return data from an Oracle stored procedure.
If you must use the PLSQL types, then you will need to create wrapper VARRAY and OBJECT TYPEs. In EclipseLink you must use a PLSQLStoredProcedureCall to access these using the code API, there is not annotation support. Or you could create your own wrapper stored procedure that converts the PLSQL types to OBJECT TYPEs, and call the wrapper stored procedure.
To map to Oracle VARRAY and OBJECT TYPEs the JDBC Array and Struct types are used, these are supported using EclipseLink ObjectRelationalDataTypeDescriptor and mappings. These must be defined through the code API, as there is currently no annotation support.
I could not find any good examples or doc on this, your best source of example is the EclipseLink test cases in SVN,
http://dev.eclipse.org/svnroot/rt/org.eclipse.persistence/trunk/foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/plsql/
http://dev.eclipse.org/svnroot/rt/org.eclipse.persistence/trunk/foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/customsqlstoredprocedures/
James : http://www.eclipselink.org -
How Do I Call PL/SQL Stored Procedure That Returns String Array??
I Have Problem Calling An Oracle(8i) Stored Procedure That Returns Array Type (Multi Rows)
(As Good As String Array Type..)
In This Fourm, I Can't Find Out Example Source.
(Question is Exist.. But No Answer..)
I Want An Example,, Because I'm A Beginner...
(I Wonder...)
If It Is Impossible, Please Told Me.. "Impossible"
Then, I'll Give Up to Resolve This Way.....
Please Help Me !!!
Thanks in advance,// Try the following, I appologize that I have not compiled and run this ... but it is headed in the right direction
import java.sql.*;
class RunStoredProc
public static void main(String args[])
throws SQLException
try
Class.forName("oracle.jdbc.driver.OracleDriver");
catch(Exception ex)
ex.printStackTrace();
java.util.Properties props = new java.util.Properties();
props.put("user", "********"); // you need to replace stars with db userid
props.put("password", "********"); // you need to replace stars with userid db password
// below replace machine.domain.com and DBNAME, and port address if different than 1521
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@machine.domain.com:1521:DBNAME", props);
// replace "Your Stored Procedure" with your stored procedure
CallableStatement stmt = conn.prepareCall("Your Stored Procedure");
ResultSet rset = stmt.execute();
while(rset.next())
System.out.println(rset.getString(1));
Maybe you are looking for
-
C8180 not working in windows 7
Printer will not fully power up. Button is green, but nothing works. Can't get computer to get out of paper jam message if I work from PC. Cannot fix message as one has to use touchpad,(showing black and no power to keypad) which is not working no
-
ITunes 8.0 only Plays One Song at a Time, then Stops! AARGH!
Someone, please help. I have tried everything I can think of, to no avail. For some reason, when I play a song in my Music Library on my laptop iTunes 8.0, it stops playing after each song. When the song ends, iTunes stops; it does not move to the ne
-
Anti Virus Software....Do I need It On My MacBook Pro??
Hi I was given the impression I didn't need anti virus software for my 1yo MacBook Pro?? am I correct or stupid? Please Help.....
-
(the original version) so that I can upgrade my system and install Logic X. I currently have 10.7.5 and a late 2011 Macbook Pro and the new Logic will not install. Can someone please steer me to find the download for 10.8?
-
Rman transportable tablespace ORA-39087: directory name is invalid
Hello all, We are trying to restore a backup of a tablepace using RMAN's TRANSPORTABLE TABLESPACE command. I created the director in oracle (and it exists on the server), granted privs yet it fails with ORA-39087: directory name is invalid. It seems