Use database inside a stored procedure
Hi guys, a stupid question: I'm working with several database and sometimes I'm afraid to run an alter or a create something in the wrong database, bear in mind that several database have the same tables. Sometime happens to run a query oin the db A
instead in the db B. So, the question: If I create a procedure like this,
create procedure creatingPillar as
use USA
begin
IF EXISTS (SELECT * FROM sys.objects WHERE object_id =
OBJECT_ID(N'pillarretail') AND type in (N'U'))
DROP TABLE PillarRetail
create table PillarRetail (anid int , ancore varchar(20), period dec(18,6), settlem datetime2,
settlementper int, asf dec(18,6),astlf dec (18,6), tot dec (18,6) )
insert into PillarRetail select anid, ancore, Period, settlem, settlementper,
asf, astlf, tot from createsemipillar2011
insert into PillarRetail select select anid, ancore, Period, settlem, settlementper,
asf, astlf, tot createsemipillar
end
but I'm wondering if is useless to put the use USA in the stored procedure by the moment that I'm creating the procedure in USA. I mean, having the SP in the USA db even if I run the procedure from another db it should run in USA. Just a stupid question
I know but I got this doubt...
Thanks
You may try as below:
create proc as below: (This will create the proc in USA database.
use USA
Go
create procedure dbo.creatingPillar as
begin
IF EXISTS (SELECT * FROM sys.objects WHERE object_id =
OBJECT_ID(N'pillarretail') AND type in (N'U'))
DROP TABLE PillarRetail
create table PillarRetail (anid int , ancore varchar(20), period dec(18,6), settlem datetime2,
settlementper int, asf dec(18,6),astlf dec (18,6), tot dec (18,6) )
insert into PillarRetail select anid, ancore, Period, settlem, settlementper,
asf, astlf, tot from createsemipillar2011
insert into PillarRetail select select anid, ancore, Period, settlem, settlementper,
asf, astlf, tot createsemipillar
end
Then you can call as below:
Exec USA.dbo.creatingPillar
Similar Messages
-
Using VIEW inside a stored procedure
Hi,
So I have a View designed in one file that validates someone who is authorized.
Then I have a stored procedure to display authorized stationeries created before a given date. Its takes a parameter @CreatedOn.
How can I use VIEW in my stored procedure so I can display all the authorized which are set 1 before a given date?
My VIEW:
ALTER VIEW vw_AuthorizedStationeries AS
SELECT Authorized
FROM dbo.Stationeries
WHERE Authorized = 1
And my stored procedure:
CREATE PROCEDURE usp_stationeries (@CreatedOn datetime)ASBEGINSELECTFROMENDGO
Thanks!Try something like below, You need to replace CreatedDate column with appropriate date column in your table.
1. Alter the view to get the required date:
ALTER VIEW vw_AuthorizedStationeries AS
SELECT Authorized, CreatedDate
FROM dbo.Stationeries
WHERE Authorized = 1
2. Alter SP:
CREATE PROCEDURE usp_stationeries (@CreatedOn datetime)
AS
BEGIN
SELECT Authorized
FROM vw_AuthorizedStationeries
WHERE CreatedDate <= @CreatedOn
END
GO
OR
You can pull required information directly from your table:
CREATE PROCEDURE usp_stationeries (@CreatedOn datetime)
AS
BEGIN
SELECT Authorized
FROM dbo.Stationeries
WHERE CreatedDate <= @CreatedOn and Authorized = 1
END
GO
If this post answers your query, please click "Mark As Answer" or "Vote as Helpful". -
Insert Multiple records using Database adapter with Stored procedure func
Hi All,
I want to insert multiple records on a database using a stored procedure. I wanted to insert those records using a Database Adapter and the Database adapter should be invoked by a Mediator.
Can somebody suggest me with ideas whether it can be acheived with OOB capabtilities in SOA suite or not?
Thanks for your help in advance.
Thanks,
ShivThe use case you want to achieve is feature supported by the DBAdapter and it is possible to invoke the same from mediator.
Please have a look at the oracle documentation and you should be able to get the necessary information.
The below links should help you as well:
http://download.oracle.com/docs/cd/E15523_01/integration.1111/e10231/adptr_db.htm
http://blogs.oracle.com/ajaysharma/2011/03/using_file_adapter_database_adapter_and_mediator_component_in_soa_11g.html
There are some video tutorials as well :)
http://www.youtube.com/watch?v=dFldS-fDx70 This should also help
Thanks,
Patrick -
Calling a function in remote database inside a stored procedure
There are 2 Oracle databases with pseudo names Remote and Local. I have a function in Remote called FUS.F_Return_10 which simply returns 10 for testing purposes, where FUS is a schema name. In Local I want to create a procedure that will call the above function. Here's the PL/SQL:
CREATE OR REPLACE PROCEDURE TEST
V_COUNT OUT NUMBER
AS
V_FOO NUMBER(2,0);
BEGIN
V_FOO:= FUS.F_Return_10@PER_ACC;
SELECT COUNT(*) INTO v_count FROM persons WHERE DEPID=V_FOO;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_count :=0;
END;
There's a Public Database Link called PER_ACC in Local. When I try to create this procedure I get: Encountered symbol "@" when expecting one of the following: .(*%&................
Can you tell me where my mistake is?Always verify your link works first by issuing:
select * from dual@dblinkname
Also do you have a private database link with the same name in the schema you are using, because the database will use this link before it uses the public link.
Also make sure the Package you are calling has execute privileges granted directly , not through a role. If your uses does not exist on the other database, you will most likely need to grant execute privilege to public.
Finally, if its not in the same schema name then you need to prefix your call with the schema name or create a public synonym for the package. -
Calling Stored procedure inside an Stored procedure
Hi,
I am working in oracle 9i. I want to call a stored procdure from another stored procedure.
Kindly provide me the example...
rgds.having a pocedure called PRCD1,
Create or Replace Procedure PRCD2 IS
egin
PRCD1;
END;
cheers !!!It will for surely err out. You cannot use "EXECUTE" inside a stored procedure.
Here's how you do it:
SQL> create or replace procedure p1 is
2 begin
3 dbms_output.put_line('I am P1');
4 end;
5 /
Procedure created.
SQL> create or replace procedure p2 is
2 begin
3 dbms_output.put_line('I am P2');
4 p1;
5 end;
6 /
Procedure created.
SQL> set serveroutput on
SQL> exec p2
I am P2
I am P1
PL/SQL procedure successfully completed.
SQL> -
Using ALTER SESSION inside a stored procedure.... not a good idea?
Hi,
I have two stored procedures, both of which are used to query a database to find a particular book, based on ISBN. One sproc searches our main product catalogue and the other searches our suppliers feed catalogues. The stored procedures are called from a C# application via a search tool and the user is able to search on either our catalogue or our suppliers. The appropriate procedure is called based on the users choices.
However, the following behaviour is observed
I search for an ISBN (is a varchar2 field, as isbn's may contain an X if the checksum digit equates to 10) on a feed, so uses the FEED SPROC. The book is found and returned to the app in about 0.5 seconds. I can repeat this as often as i like on different books etc. always works fine.
I then do the same search but against our own catalogue, so uses our CATALOGUE SPROC. Again the book is found quickly, and the search can be repeated with the same results.
If i then go back and run our FEED SPROC then the search time increases to about 3 minutes !
Both the feed and our catalogue is in the same database, although different schema's the connections will be pooled through our app server.
I can repliacte this every single time. I think i have narrowed doen the cause of this behaviour to a few lines of code in our CATALOGUE SPROC:
-- store values
select value into v_vch_NLS_COMP from nls_session_parameters nsp where nsp.parameter = 'NLS_COMP';
select value into v_vch_NLS_SORT from nls_session_parameters nsp where nsp.parameter = 'NLS_SORT';
-- Ensure case insensitivity throughout
EXECUTE IMMEDIATE 'ALTER SESSION SET NLS_COMP = LINGUISTIC';
EXECUTE IMMEDIATE 'ALTER SESSION SET NLS_SORT = BINARY_CI';
do other stuff
-- restore session variables
EXECUTE IMMEDIATE 'ALTER SESSION SET NLS_COMP = ' || v_vch_NLS_COMP;
EXECUTE IMMEDIATE 'ALTER SESSION SET NLS_SORT = ' || v_vch_NLS_SORT;
If i remove this code then all is well, so i am assuming that using ALTER SESSION inside a stored procedure is the cause of the problem as it would be changing the execution plan of the FEEDS SPROC in some manner? Any ideas? I know i can just rewrite the sproc to avoid using this coding, but wanted to understand if i am doing something wrong by using ALTER SESSION in this manner?
Any pointers would be appreciated.
John Thompson
Software Architect,
play.com
Edited by: user7186902 on 27-May-2009 03:51Hello (and welcome),
It may be a case of having to create a linguistic index to facilitate the queries once you set these session level parameters, i.e..,
CREATE INDEX idx_01 ON tab ((NLSSORT(col1, 'NLS_SORT=BINARY_CI'))It would appear that the setting of those parameters is invalidating index searching on the current indexes. -
SQL Server Free Text Search with multiple search words inside a stored procedure
I am trying to do a free text search. basically the search string is being sent to a stored procedure where it executes the free text search and returns the result.
If I search for red
flag, I want to return the results that matches both red and flag text.
Below is the query I use to return the results.
select * from customer where FREETEXT (*, '"RED" and "flag"')
This doesn't give me the desired result. Instead this one give the desired result.
select * from customer where FREETEXT (*, 'RED') AND FREETEXT (, 'FLAG')
My problem is since it's inside a stored procedure, I will not be able to create the second query where clause. I thought both query should return the same result. Am I doing something wrong here?I am moving it to Search.
Kalman Toth Database & OLAP Architect
IPAD SELECT Query Video Tutorial 3.5 Hours
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
Query to get list of linked server tables referenced inside a stored procedure
Hi,
SQL Server 2005 sp4
I have a requirement to get list of linked server tables referenced insider a stored procedure
Ex:
Databases DB1 DB2
Tables: T1 T2
Use DB1
Go
Create proc P1
begin
select * from T1
select * from DB2.dbo.T2
end
I am looking for a query which can return a result with output as below. sp_depends is not helping here as it does not work for cross DB objects, any other thoughts.
Tables
T1,
DB2.dbo.T2On SQL 2005, you will have to do it manually.
On SQL 2008 or later, you could have used sys.sql_expression_dependencies.
Erland Sommarskog, SQL Server MVP, [email protected] -
Extract data in to excel inside a stored procedure
Hi,
Is there a way to extract data from a table in to excel inside a stored procedure and not using SSIS?
Thanks,
PreethaHere's a similar, simpler, sample.
Sub TestMacro()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=(local);INITIAL CATALOG=NORTHWIND.MDF;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "SELECT * FROM Categories"
' Copy the records into cell A1 on Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub
Finally, this answers you exact question.
Option Explicit
Sub Working2()
'USE [Northwind]
'GO
'DECLARE @return_value int
'EXEC @return_value = [dbo].[TestNewProc]
' @ShipCountry = NULL
'SELECT 'Return Value' = @return_value
'GO
Dim con As Connection
Dim rst As Recordset
Dim strConn As String
Set con = New Connection
strConn = "Provider=SQLOLEDB;"
strConn = strConn & "Data Source=LAPTOP\SQL_EXPRESS;"
strConn = strConn & "Initial Catalog=Northwind;"
strConn = strConn & "Integrated Security=SSPI;"
con.Open strConn
'Put a country name in Cell E1
Set rst = con.Execute("Exec dbo.TestNewProc '" & ActiveSheet.Range("E1").Text & "'")
'The total count of records is returned to Cell A5
ActiveSheet.Range("A5").CopyFromRecordset rst
rst.Close
con.Close
End Sub
Sub Working()
'USE [Northwind]
'GO
'DECLARE @return_value int
'EXEC @return_value = [dbo].[Ten Most Expensive Products]
'SELECT 'Return Value' = @return_value
'GO
Dim con As Connection
Dim rst As Recordset
Set con = New Connection
con.Open "Provider=SQLOLEDB;Data Source=LAPTOP\SQL_EXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;"
Set rst = con.Execute("Exec dbo.[Ten Most Expensive Products]")
'Results of SProc are returned to Cell A1
ActiveSheet.Range("A1").CopyFromRecordset rst
rst.Close
con.Close
End Sub
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it. -
Can rs.last() be used after calling the stored procedure?
Can rs.last() be used after calling the stored procedure? If yes what should be the CURSOR types?
Can rs.last() be used after calling the stored
procedure? If yes what should be the CURSOR types?That would depend on the driver/database.
And as I said in your other post it is far more efficient to count records by just returning a count rather than a complete collection regardless of how you get to the end. -
How Create a Global Temporary Table inside a Stored Procedure?
Hi...
I need to create a Global Temporary Table inside a Stored
Procedure....
I have no idea how to do that....
Please....if u can send me a sample, send to me....
Thanks a lotthere are many ways to do this..
one u can use dbms_utility package to run ddl statements like
for ex:
declare
t varchar2(200):='order_no';
v number;
begin
--dbms_utility.exec_ddl_statement('select '||t||' into '||v||'
from
--ordermaster where rownum=1');
dbms_utility.exec_ddl_statement('create table cvt(t number)');
dbms_output.put_line(v);
end;
but the actual method(recommended) involves a bit coding using
dbms_sql package you will find examples on technet or metalink
to use this package..
I hope this helps
Narendra -
Using Copy statement in Stored procedure
The following statement works in sqlplus session:
copy from comment/password@servername append amcomment_temp using
select * from amcomment
where commentid in(1,2,3,4)
I want to use this in a stored procedure. There is a long datatype in this table. The
procedure will not compile. Have tried execute immediate and compiler rejects this statement also.'COPY' is a SQL*Plus command, not PL/SQL. This is why the PL/SQL compiler throws it out.
-
How can i create a Global Temporary Table inside a Stored Procedure....
Hi...
I need to create a Global Temporary Table inside a Stored
Procedure....
I have no idea how to do that....
Please....if u can send me a sample, send to me....
Thanks a lotTo create a global temporary table inside a stored procedure,
the minimal syntax would be:
CREATE OR REPLACE PROCEDURE procedure_name
AS
BEGIN
EXECUTE IMMEDIATE 'CREATE GLOBAL TEMPORARY TABLE table_name'
|| '(column_name NUMBER)';
END procedure_name;
As Todd stated, it would probably be better to create the global
temporary table outside of the procedure:
SQL> CREATE GLOBAL TEMPORARY TABLE table_name
2 (column_name NUMBER);
Table created.
You can also specify things like ON COMMIT PRESERVE ROWS or ON
COMMIT DELETE ROWS.
It may be that there is something else, like a PL/SQL table of
records or a cursor, that would suit your needs better. It is
difficult to guess without knowing what you want to do with it. -
How to use order by in stored procedure base block?
How to use order by in stored procedure base block? I need to change order by dynamically
Use SET_BLOCK_PROPERTY('BLOCK_NAME',ORDER_BY,'COLUMN_NAME1, COLUMN_NAME2');
-
Using temporary tables in stored procedures
Suppose that I have created a temporary table in a stored procedure using an "EXECUTE IMMEDIATE" statement. When I compile the procedure, that table is not created yet, so the compiler says that the table does not exist.
What is the way of using temporary tables in stored procedures?It's a good practice to avoid using DDL statements being executed from stored procedures. "Truncate Table" via dynamic SQL from stored procedure is a different story and is useful in DSS environments.
But if you insist on "creating" tables using Dynamic SQL from Stored Procedures then you must also embed your DML statements in Dynamic SQL to avoid compilation errors.
Example:
Create or Replace Procedure Proc_TestDynamicSQL is
Begin
Execute Immediate 'Create table myTable as select * from user_tables' ;
Execute Immediate 'Update myTable set table_name = ''Test'' ' ; --two single quotes before and after the string "Test"
End;
In this case, Oracle wouldn't care about the table references during compilation.
Maybe you are looking for
-
I need help bout iOS 7 on iPad it's saying I gotta visit http:support.apple.com I went in there n still no help
-
Archiving mailbox folders to an external HDD - How?
I have a Mac Bool Pro and I have a large number of mailbox folders that I do not use very much. I would like to offload these folders to a large external HDD and remove them from the internal HDD of the Macbook pro...how do I do this ? I also then wa
-
Still photo in FCP exported to Photoshop, not matching aspect ratio
Hi, I made a still photo in FCP. Sent to Photoshop. Imported back in FCP. Image is squished. I am using DV NTSC 720x480. In Photoshop I also set Image Size to 720x480. For some reason I cant get it to match in FCP. Any idea how I an fix this? Thanks.
-
Can I download and reactivate the old version of Keynote?
I tried to use Keynote 13, it, however, is driving me crazy. Many of smart build were broken, and I cannot use the toolbar I customized. Because of the tons of reason, I wanna use old version of Keynote again. Can I download and re-activate the old v
-
Different between Dual hub-dual DMVPN cloud Vs Dual hub-single DMVPN cloud
please explain different between Dual hub-dual DMVPN cloud Vs Dual hub-single DMVPN cloud