DDL statements and dynamic sql in stored procedure
I created a stored procedure to create and drop tables, using dynamic sql.
When I try to do the inserts using dynamic sql, i.e
v_string := 'INSERT statement';
EXECUTE IMMEDIATE v_string;
I get the following error message:
ERROR at line 1:
ORA-00942: table or view does not exist
ORA-06512: at line 63
Line 63 happens to be the line that the EXECUTE IMMEDIATE v_string; statement is in.
I am able to describe the table that the inserts are being made into, so I know that the table exists.
Any idea why I'm getting this error message would be appreciated.
Yes I do and I have been able to create other tables using dynamic sql.
The table that I am having problems with SELECTs data from another table to get its column values; within the SELECT statement, the CAST function is used:
ie. CAST(CASE SUBSTR(CAST(E_MOD AS VARCHAR(7)),2,3)
WHEN 'AAA' THEN 'A55'
ELSE ............
I get the following error message:
ERROR at line 18: (this line starts the CAST statement)
ORA-06550: line 18, column 13:
PLS-00103: Encountered the symbol "AAA" when expecting one of the following:
. ( * @ % & = - + ; < / > at in is mod not rem return
returning <an exponent (**)> <> or != or ~= >= <= <> and or
like between into using || bulk
When I remove the quotes or add another single quote, the same error cascades to 'A55'.
After doing the same for the next error, I get the error message below:
ERROR at line 1: (this line has the EXECUTE IMMEDIATE statement)
ORA-00936: missing expression
ORA-06512: at line 6
Any idea what the problem could be?
Also is there another way to have DDL statements as stored procedures other than using dynamic sql or the DBMS_SQL package?
Similar Messages
-
Performance between SQL Statement and Dynamic SQL
Select emp_id
into id_val
from emp
where emp_id = 100
EXECUTE IMMEDIATE
'Select '|| t_emp_id ||
'from emp '
'where emp_id = 100'
into id_valWill there be more impact in performance while using Dynamic SQL?CP wrote:
Will there be more impact in performance while using Dynamic SQL?All SQLs are parsed and executed as SQL cursors.
The 2 SQLs (dynamic and static) results in the exact same SQL cursor. So both methods will use an identical cursor. There are therefore no performance differences ito of how fast that SQL cursor will be.
If an identical SQL cursor is not found (a soft parse), the SQL engine needs to compile the SQL source code supplied, into a SQL cursor (a hard parse).
Hard parsing burns a lot of CPU cycles. Soft parsing burns less CPU cycles and is therefore better. However, no parsing at all is the best.
To explain: if the code creates a cursor (e.g. INSERT INTO tab VALUES( :1, :2, :3 ) for inserting data), it can do it as follows:
while More Data Found loop
parse INSERT cursor
bind variables to INSERT cursor
execute INSERT cursor
close INSERT cursor
end loopIf that INSERT cursor does not yet exists, it will be hard parsed and a cursor created. Each subsequent loop iteration will result in a soft parse.
However, the code will be far more optimal as follows:
parse INSERT cursor
while More Data Found loop
bind variables to INSERT cursor
execute INSERT cursor
end loop
close INSERT cursorWith this approach the cursor is parsed (hard or soft), once only. The cursor handle is then used again and again. And when the application is done inserting data, the cursor handle is released.
With dynamic SQL in PL/SQL, you cannot really follow the optimal approach - unless you use DBMS_SQL (a complex cursor interface). With static SQL, the PL/SQL's optimiser can kick in and it can optimise its access to the cursors your code create and minimise parsing all together.
This is however not the only consideration when using dynamic SQL. Dynamic SQL makes coding a lot more complex. The SQL code can now only be checked at execution time and not at development time. There is the issue of creating shareable SQL cursors using bind variables. There is the risk of SQL injection. Etc.
So dynamic SQL is seldom a good idea. And IMO, the vast majority of people that post problems here relating to dynamic SQL, are using dynamic SQL unnecessary. For no justified and logical reasons. Creating unstable code, insecure code and non-performing code. -
Dynamic Execution of Stored Procedure
Hi Everybody!
I have two questions for you. All my questions are pertaining PL/SQL programming with Oracle 8i. But before that, I would like to introduce a bit about the background.
We have .NET based application, which calls some 80 odd Oracle stored procedures one after one. The input parameters for all these stored procedure are same i.e. two IN parameters of Integer type and a OUT parameter of cursor type. The name of these stored procedures are listed in table (let say tblSPTable). We use to get the list of stored procedures from this table and execute them one after one.
Sooner or later we realized that, this way of calling the stored procedures is causing a performance issue. So, we thought of moving the call to all these stored procedures to a new stored procedure. We thought of giving a call to this new stored procedure, which will in turn execute all these stored procedures one after one (by using the tblSPTable), and return us the all the cursors at one shot. But here is where we got stuck:
How can I declare a OUT parameter for a list of cursors? Because I need to store the output of all the 80 odd calls in different cursors and have to get it back. I have tried to declare VARRAY of cursors or TABLE of cursors but it is not supported. One way of doing this is to declare all the 80 cursors as OUT parameters in the new stored procedure, but that is absolutely a bad programming practice. Apart from that, in future if we want to modify the order of the stored procedure, OR if we want to add or remove few stored procedures listed in tblSPTable, we have to modify this new procedure every time. My question is how can I declare or use a variable which can hold the list of cursors, which I can use from a .NET base application.
Secondly, I will get the name of all the stored procedure by querying the tblSPTable, and will execute them dynamically. I have tried out something like this but not succeeded
declare
cur_result some_package.some_cursor;
var_spname varchar;
begin
var_spname:=’pr_some_procedure’;
execute immediate 'begin ‘ || var_spname || ‘(:2); end;' using out cur_result;
end;
Bur, I am getting an error saying “Error while trying to retrieve text for error ORA-03113”. I have scanned through few docs available over net, but none of them are really helpful. My question is how can I dynamically execute a stored procedure which has a cursor as a OUT parameter.
Please help me out if you people have any idea regarding this. Please let me know whether my approach is correct or not. I am waiting for your valuable suggestions.
Thanking you
Ayan Mitra
Message was edited by:
user588628your solution will work out only in case all the functions returning you a cursor which holds same number of columnNot so. It is unfortunate that my example does not make that clear.
The UNION ALL is of a single column which is of type weak refcursor.
By way of example the below changes the p_dept procedure so it returns two columns rather than three.
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production
SQL> CRE ATE OR REPLACE PROCEDURE p_dept (
2 p_deptno IN dept.deptno%type,
3 p_resultset OUT SYS_REFCURSOR)
4 IS
5 BEGIN
6 OPEN p_resultset FOR
7 SELECT d.deptno, d.dname
8 FROM dept d
9 WHERE d.deptno = p_deptno;
10 END p_dept;
11 /
Procedure created.
SQL> VARIABLE p_resultset REFCURSOR;
SQL> BEGIN
2 :p_resultset := f_all (
3 p_deptno => 30,
4 p_functions => varchar2_table ('F_DEPT', 'F_EMP'));
5 END;
6 /
PL/SQL procedure successfully completed.
SQL> PRINT p_resultset;
RN FN RS
1 F_DEPT CURSOR STATEMENT : 3
CURSOR STATEMENT : 3
DEPTNO DNAME
30 SALES
2 F_EMP CURSOR STATEMENT : 3
CURSOR STATEMENT : 3
EMPNO ENAME JOB
7499 ALLEN SALESMAN
7521 WARD SALESMAN
7654 MARTIN SALESMAN
7698 BLAKE MANAGER
7844 TURNER SALESMAN
7900 JAMES CLERK
6 rows selected.
SQL>[pre] -
I have used a tool to convert my sql 2000 stored procedure to Oracle 10g PL/SQL, here is an example
SQL 2000 Stored Procedure
CREATE PROCEDURE [GetEmployees]
AS
Select * from EMPMST ORDER BY emp_name
GO
After Transformation i got 2 files, one was a procedure and other a package
CREATE OR REPLACE PACKAGE GLOBALPKG
AS
TYPE RCT1 IS REF CURSOR;
TRANCOUNT INTEGER := 0;
IDENTITY INTEGER;
END;
CREATE OR REPLACE PROCEDURE GetEmployees
RCT1 IN OUT GLOBALPKG.RCT1
AS
BEGIN
OPEN RCT1 FOR
SELECT *
FROM EMPMST
ORDER BY emp_name;
END;
When i execute the procedure GetEmployees i got this error :
SQL> execute GetEmployees;
BEGIN GetEmployees; END;
ERROR at line 1:
ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'GETEMPLOYEES'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Please Help me in debugging this error. Thanks in advance.As the poster above mentioned you cannot call "GetEmployees" without a parameter.
Note that the procedure declaration has the following line
RCT1 IN OUT GLOBALPKG.RCT1
This means that whenever you want to call the procedure you must pass it a variable of type GLOBALPKG.RCT1
However unless this is merely a homework or learning exercise (i.e. you are not porting the code of a production application) i would strongly recommend that you do not attempt to simply convert the code to PL/SQL.
The reasoning behind this is that Oracle's architecture will be completely different to the source of the original code and if you attempt to simply port the code (especially using an automatic tool) you will almost certainly hit problems.
For example the SQL Server's 2000 code may (should be) be written based on SQL Server's locking strategy. Oracle's locking strategy is completly different if you try to use the same techniques as you do in SQL Server the performance will suffer.
Porting a code or a database schema from one platform to another involves a lot of analysis in order to take advantage of the features of the destination platform.
As I said this may not be important to you depending on why you are attempting a port.
Good Luck. -
How to call a sql server stored procedure from oracle
Hi all,
Please anybody tell me how to call a sql server stored procedure from oracle.
I've made an hsodbc connection and i can do insert, update, fetch data in sql server from oracle. But calling SP gives error. when I tried an SP at oracle that has line like
"dbo"."CreateReceipt"@hsa
where CreateReceipt is the SP of sql server and hsa is the DSN, it gives the error that "dbo"."CreateReceipt" should be declared.
my database version is 10g
Please help me how can i call it... I need to pass some parameters too to the SP
thanking youhi,
thank you for the response.
when i call the sp using DBMS_HS_PASSTHROUGH, without parameters it works successfully, but with parameters it gives the following error
ORA-28500: connection from ORACLE to a non-Oracle system returned this message:
[Generic Connectivity Using ODBC][Microsoft][ODBC SQL Server Driver]Invalid parameter number[Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index (SQL State: S1093; SQL Code: 0)
my code is,
declare
c INTEGER;
nr INTEGER;
begin
c := DBMS_HS_PASSTHROUGH.OPEN_CURSOR@hsa;
DBMS_HS_PASSTHROUGH.PARSE@hsa(c, 'Create_Receipt(?,?)');
DBMS_HS_PASSTHROUGH.BIND_VARIABLE@hsa(c,1,'abc');
DBMS_HS_PASSTHROUGH.BIND_VARIABLE@hsa(c,2,'xyz');
nr:=DBMS_HS_PASSTHROUGH.EXECUTE_NON_QUERY@hsa(c);
DBMS_HS_PASSTHROUGH.CLOSE_CURSOR@hsa(c);
end;
Create_Receipt is the sp which requires two parameters.
please give me a solution
thanking you
sreejith -
Passing dynamic parameter to stored procedure from CR formula?
Dear all,
I need to insert in some textboxes the right string based on the desired Language Code.
I crated a stored procedure in my db.
CREATE PROCEDURE MY_GET_TRANSLATION
@TextID nvarchar(8),
@LangCode int
This parameters are used as keys to get the Trans field.
I created a workshop formula: GetTranslation
Please, can someone suggest the correct statement to call my MY_GET_TRANSLATION stored procedure passing parameters?
I would like to call the GetTranslation formula from all my textboxes, passing the specific TextID value
and visualized the right translated string.
For example:
in my TEXT1 textbox, I would like to call the GetTranslation formula passing the parameters
TextID = "T000001"
and
LangCode = 13 (Italian language)
How can pass dynamic parameters to a formula?
How can pass dynamic parameters to a stored procedure from a CR formula?
Regards
EmanueleDear Jason,
I'm trying to modify a SAP B1 CR marketing report.
This CR marketing document is called by SAP B1 automatically passing the Document Number and Document Type.
The report uses the right SAP B1 tables to read the information of the header and rows of the document.
The language of the document is contained in a field of the header table
{MyMarketingDocTable.LanguageID}
I created a user table named "MyTranslationTable" where I added some strings in different langiages.
For example:
TexiID TextString LangID
T00001 Delivery 8
T00001 Consegna 13 (Italian translation)
T00002 Invoice 8
T00002 Fattura 13 (Italian translation)
In the header of the report I'd like, for example, to visualise the string "Consegna" if my document is a delivery in italian language.
I'd like to implement this method to translate all the textboxes (header, comments, etc.) based on the languageID of my document.
For each textboxes, in the CR designer statically I know what TextID I want to visualized but dinamically I need to pass to my stored procedure the right language. I'd like my report automatically gets the language at run-time. I don't want that when I press the Print-preview button in SAP B1, the report asks to prompt the languageID.
It already read the DocNum and DocType and it already filter the SAP B1 tables basing on the DocNum and DocType of the document. In this way it reads the right row in the SAP B1 table and in this way I can read all the fields of this row (also the languageID of the actual document).
Regards
Emanuele
Edited by: Emanuele Croci on Dec 3, 2010 9:03 AM -
Converting SQL Server Stored Procedure to Oracle
Hi there,
I tried to use SwisSQL to convert my SQL Server stored procedure to Orcale without much success.
Is there anyone who could help me out with this?
My SQL Server Stored Procedure is:
CREATE PROCEDURE [dbo].[SP_BackgroundCheckRequest]
--MASTER Table
@MASTER_ID int,
@PERSONNEL_ID int = NULL,
@DATE_OF_BIRTH datetime = NULL,
@GENDER varchar(1) = NULL,
@COUNTRY_OF_BIRTH varchar(3) = NULL,
@TOWN_OF_BIRTH varchar(100) = NULL,
@STATE_OF_BIRTH varchar(50) = NULL,
@CHECK_CATEGORY varchar(10) = NULL,
@CHECK_TYPE varchar(10) = NULL,
@PRIORITY varchar(10) = NULL,
@PRIORITY_REASON varchar(100) = NULL,
@SCREENING_LEVEL nchar(1) = NULL,
@POSITION nchar(50) = NULL,
@REQUEST_SOURCE varchar(60) = NULL,
--NAME_TYPE Table
@NAME_TYPE varchar(5) = NULL,
@FAMILY_NAME varchar(50) = NULL,
@FIRST_NAME varchar(50) = NULL,
@MIDDLE_NAME varchar(50) = NULL,
@TITLE varchar(10) = NULL,
@PREFFERED_NAME varchar(40) = NULL,
@PREVIOUS_NAME varchar(140) = NULL,
--ADDRESS_TYPE Table
@ADDRESS_TYPE varchar(10) = NULL,
@ADDRESS_LINE_1 varchar(30) = NULL,
@ADDRESS_LINE_2 varchar(30) = NULL,
@ADDRESS_LINE_3 varchar(30) = NULL,
@COUNTRY varchar(3) = NULL,
@SUBURB varchar(50) = NULL,
@STATE varchar(50) = NULL,
@POSTCODE varchar(15) = NULL,
@START_DATE varchar(10) = NULL,
@END_DATE varchar(10) = NULL,
--LICENSE_TYPE Table
@LICENSE_TYPE varchar(5) = NULL,
@LICENSE_AGENCY varchar(15) = NULL,
@LICENSE_NUMBER varchar(100) = NULL,
@LICENSE_SIGHTED varchar(1) = NULL,
--PHONE_TYPE Table
@TELEPHONE_TYPE varchar(5) = NULL,
@TELEPHONE_NUMBER varchar(20) = NULL,
@MOBILE_TYPE varchar(5) = NULL,
@MOBILE_NUMBER varchar(20) = NULL,
@EXTENSION_TYPE varchar(5) = NULL,
@EXTENSION_NUMBER varchar(20) = NULL,
--PASSPORT_TYPE Table
@PASSPORT_TYPE varchar(5) = NULL,
@PASSPORT_NUMBER varchar(50) = NULL,
@PASSPORT_COUNTRY varchar(3) = NULL,
@PASSPORT_SIGHTED varchar(1) = NULL
AS
BEGIN TRANSACTION
INSERT into MASTER (MASTER_ID, PERSONNEL_ID, DATE_OF_BIRTH, GENDER, COUNTRY_OF_BIRTH,
TOWN_OF_BIRTH, STATE_OF_BIRTH, CHECK_CATEGORY, CHECK_TYPE, PRIORITY, PRIORITY_REASON,
SCREENING_LEVEL, POSITION, REQUEST_SOURCE)
VALUES (@MASTER_ID, @PERSONNEL_ID, @DATE_OF_BIRTH, @GENDER, @COUNTRY_OF_BIRTH,
@TOWN_OF_BIRTH, @STATE_OF_BIRTH, @CHECK_CATEGORY, @CHECK_TYPE, @PRIORITY, @PRIORITY_REASON,
@SCREENING_LEVEL, @POSITION, @REQUEST_SOURCE)
IF @@ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error inserting values into MASTER table!', 16, 1)
RETURN
END
INSERT into NAME_TYPE (MASTER_ID,NAME_TYPE,FAMILY_NAME,FIRST_NAME,MIDDLE_NAME,TITLE)
VALUES (@MASTER_ID,@NAME_TYPE,@FAMILY_NAME,@FIRST_NAME,@MIDDLE_NAME,@TITLE)
IF @@ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error inserting values into NAME_TYPE table!', 16, 1)
RETURN
END
INSERT into ADDRESS_TYPE (MASTER_ID,TYPE,ADDRESS_LINE_1,ADDRESS_LINE_2,ADDRESS_LINE_3,
COUNTRY,SUBURB,STATE,POSTCODE,START_DATE,END_DATE)
VALUES (@MASTER_ID,@ADDRESS_TYPE,@ADDRESS_LINE_1,@ADDRESS_LINE_2,@ADDRESS_LINE_3,
@COUNTRY,@SUBURB,@STATE,@POSTCODE,@START_DATE,@END_DATE)
IF @@ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error inserting values into ADDRESS_TYPE table!', 16, 1)
RETURN
END
INSERT into LICENSE_TYPE (MASTER_ID,TYPE,AGENCY,NUMBER,SIGHTED_YN)
VALUES (@MASTER_ID,@LICENSE_TYPE,@LICENSE_AGENCY,@LICENSE_NUMBER,@LICENSE_SIGHTED)
IF @@ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error inserting values into LICENSE_TYPE table!', 16, 1)
RETURN
END
INSERT into PHONE_TYPE (MASTER_ID,TYPE,NUMBER)
VALUES (@MASTER_ID,@TELEPHONE_TYPE,@TELEPHONE_NUMBER)
IF @@ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error inserting Telephone number into PHONE_TYPE table!', 16, 1)
RETURN
END
IF ((@MOBILE_TYPE <> NULL) AND (@MOBILE_NUMBER <> NULL))
BEGIN
INSERT into PHONE_TYPE (MASTER_ID,TYPE,NUMBER)
VALUES (@MASTER_ID,@MOBILE_TYPE,@MOBILE_NUMBER)
IF @@ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error inserting Mobile number into PHONE_TYPE table!', 16, 1)
RETURN
END
END
IF ((@EXTENSION_TYPE <> NULL) AND (@EXTENSION_NUMBER <> NULL))
BEGIN
INSERT into PHONE_TYPE (MASTER_ID,TYPE,NUMBER)
VALUES (@MASTER_ID,@EXTENSION_TYPE,@EXTENSION_NUMBER)
IF @@ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error inserting Extension number into PHONE_TYPE table!', 16, 1)
RETURN
END
END
INSERT into PASSPORT_TYPE (MASTER_ID,NUMBER,COUNTRY,SIGHTED_YN)
VALUES (@MASTER_ID,@PASSPORT_NUMBER,@PASSPORT_COUNTRY,@PASSPORT_SIGHTED)
IF @@ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error inserting values into PASSPORT_TYPE table!', 16, 1)
RETURN
END
COMMITFirst, a basic concept. That also illustrates how different Oracle is (and PL/SQL) from SQL-Server (and T-SQL).
PL/SQL integrates two different languages. The PL language. The SQL language. It allows you to code SQL source code natively inside the PL language. The PL compiler is clever enough to do the rest - make calls to the SQL engine to create SQL cursors, bind PL variable values to bind variables in the SQL code. Etc.
PL is a "proper" programming language. It is much like Pascal (it is based on Ada, a close family member of Pascal). It is nothing at all like T-SQL.
Okay, now for the very basic rule for Oracle development.
Maximize SQL. This means using the SQL language to crunch data. It is the "closest" to the data. It is designed and optimised for dealing with data. Do your data processing using SQL.
Minimize PL/SQL. This means using the PL language not to crunch data, but to provide the conditional logic. Implement business rules. And then have the SQL language crunch the data as the data processing language.
Attempting to directly translate T-SQL code into PL/SQL is flawed. It is like trying to make coffee with teabags. Yeah, the tea may have caffeine it, but it is not coffee.
To do what that T-SQL script does, insert a row into a table, a typical PL/SQL equivalent will look as follows:
create or replace procedure InsertMaster( masterRow master%rowtype ) authid definer is
.. types and variables declared here
begin
-- masterRow is a record structure that matches the actual MASTER table
.. apply business rules and validation to the data.. raising user exceptions as needed
-- e.g. the POSITION column must be upper case
masterRow.position := upper(masterRow.position);
-- after the business logic and data validation we can add the row to the table
-- (PL will make the INSERT call to the SQL engine)
insert into master values masterRow;
end;No commit. The caller does the business transaction. It needs to decide when to commit to maintain the integrity of the data in the database. It may need to do several more calls, before committing.
With this approach, we can give the application schema (the caller) execute privs on this procedure. This procedure is defined with definer rights. This means it runs with the privs of owner of that procedure and MASTER table. It is trusted code. It does all the correct stuff to add a valid and checked row to the MASTER table. So we give the app schema execute privs on the procedure and no insert priv on the MASTER table.
The only way the caller can add row to the MASTER table is via this trusted procedure of ours.
And this is a typical approach in Oracle - using the PL/SQL (both PL language and SQL language) code to create an interface to a logical database in Oracle. Abstracting the complexities of SQL from the caller. Moving business and validation into PL. Allowing us the flexibility of modifying business and validation logic, without touching a single byte of caller/client code. Allowing us to manage and tune SQL performance without dealing with (badly designed and coded) SQL from a client - as the SQL resides in PL/SQL packages and procedures and functions. -
How to run a SQL Server Stored Procedure
I need to run a SQL Server Stored Procedure in answer, the stored procedure use a hash table (temporary table) and I nedd to pass a parameter to stored procedure
anyone know if is it possible in OBIEE, if yes how.
thank you
maxthank you, but I'm not understand what you mean. I need to run this command in answer "direct access database"
exec storedprocedure 1,1,1
if I run this I receive thi error:
error : [nQSError: 16001] ODBC error state: S0002 code: 208 message: [Microsoft][ODBC SQL Server Driver][SQL Server]object name '#TempList' not valid.. [nQSError: 16002] Cannot obtain number of columns for the query result. (HY000).
here is the code of stored procedure:
ROC [dbo].[GetOrderListmax]
@OrderList varchar(500)
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #TempList
OrderID int
DECLARE @OrderID varchar(10), @Pos int
SET @OrderList = LTRIM(RTRIM(@OrderList))+ ','
SET @Pos = CHARINDEX(',', @OrderList, 1)
IF REPLACE(@OrderList, ',', '') <> ''
BEGIN
WHILE @Pos > 0
BEGIN
SET @OrderID = LTRIM(RTRIM(LEFT(@OrderList, @Pos - 1)))
IF @OrderID <> ''
BEGIN
INSERT INTO #TempList (OrderID) VALUES (CAST(@OrderID AS int)) --Use Appropriate conversion
END
SET @OrderList = RIGHT(@OrderList, LEN(@OrderList) - @Pos)
SET @Pos = CHARINDEX(',', @OrderList, 1)
END
END
SELECT o.OrderID, CustomerID, EmployeeID, OrderDate
FROM dbo.Orders AS o
JOIN
#TempList t
ON o.OrderID = t.OrderID
END -
Drop and recreate table in stored procedure
Hi all
When creating tables using Transact-SQL scripts, I have always preferred to drop the table if it exists and then create it explicitly using CREATE TABLE. For two reasons:
1) It does not matter if it is the first time the SP is run ie. if I create the table manually in the first instance and just use TRUNCATE TABLE it could fail if the table is deleted
2) I have control over the data types of the table fields
Just recently though I discovered the error that can occur when dropping and creating a table in the same batch (see link below)
Microsoft Website
This causes me a problem when dropping and creating tables in stored procedures, as I understand that a stored procedure is in itself a single batch?
Can I avoid this error in a stored procedure whilst continuing to drop and create tables? Or should I be taking a different approach?
Coding best practice advice would be greatly appreciated.
Thank youThanks Ronen
Please see my second post immediately before your reply.
Given that I need to store the data output in a physical table for use in QlikView, would you suggest truncating the table each time the SP runs? And then having a script that handles both dropping and creating the physical table, and also creating
the SP?
>> QlikView
QlikView is an Israeli company, right?
In any case I am not familiar with QlikView's application, therefore I can only give you general information, based on assumptions regarding the application, and facts regarding the SQL Server.
>> for use in QlikView
I assume that external application use specific database structure (table
structure) and it is change only in rare situations (for example CMS interface might change the tables if and when a module s update/install). In this case there is no need to drop the table and recreate it and TRUNCATE is the solution.
>> would you suggest truncating the table each time the SP runs
I am sorry but i cant recommend on TRUNCATE a table each time you execute SP, without know the exact reason for this logic. It sound to me, at this point of time (with the information that we have), that this
is very bad logic (application architecture). As I wrote above, basing your application on TRUNCATING the table each time mean that you have problems with multi users. Thins about 2 people that try to execute the same SP at almost the same time. Think about
locking in the SQL Server and bad data (one truncate while the other already inserted the new data and get no rows, if there is no locking).
But TRUNCATE is much better in this case probably then DROP and DELETE, since it is faster, and locking will be shorter (hopefully the application use the correct locking). There are other reasons why TRUNCATE is better, and other people already mentioned
most of them, but time in this scenario might be critical.
>> having a script that handles both dropping and creating the physical table, and also creating the SP?
I do not undestand what is this second step. we said that you truncate the table, so why do you need to
dropping and creating the physical table and who
creating the SP?
Are you meaning that the application create the tables and SP?
There are lot of application that during installation create the database structure. is this what you mean?
Ronen Ariely
[Personal Site] [Blog] [Facebook] -
Can a SQL Server stored procedure call an SAP function module?
Can a SQL Server stored procedure call an SAP function module.? The stored procedure will be called via a trigger when data records are added to a Z table.
You have two options:
- the other software can use the RFC SDK and call directly in the system
- the other software can use a database connect
Markus -
Difference between Static SQL Query and Dynamic SQL Query.
Hi,
Please explain the basic difference between static and dynamic sql queries. Please explain with example.Static: http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/static.htm
Dynamic: http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/dynamic.htm -
Hi Team,
I need to write a SQL to cater the requirements. Below is my requirements:
pagename fieldname fieldvalue account_number consumerID
AFAccountUpdate ArrangementsBroken dfsdff 1234 1234
AFAccountUpdate ArrangementsBroken1 dfsdff 1234 1234
AFAccountUpdate ArrangementsBroken2 dfsdff 1234 1234
AFAccountUpdate ArrangementsBroken2 dfsdff 12345 12345
AFAccountUpdate ArrangementsBroken1 addf 12345 12345
Create table test_pivot_dynamic
pagename varchar(200),
fieldname Varchar(200),
fieldvalue varchar(500),
N9_Router_Account_Number bigint,
TC_Debt_Item_Reference bigint
--Input
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken','addf',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken1','dfsdff',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken2','fder',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken2','dfdfs',12345,12345)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken1','dfdwe',12345,12345)
insert into test_pivot_dynamic Values('AFAccountUpdate1','Arrangements','addf',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate1','Test1','dfsdff',1234,1234)
--Expected output:
Select 1234,1234,'AFAccountUpdate','ArrangementsBroken','addf','ArrangementsBroken1','dfsdff','ArrangementsBroken2','fder','ArrangementsBroken2','fder'
Select 12345,12345,'AFAccountUpdate','ArrangementsBroken','addf','ArrangementsBroken1','dfdwe','ArrangementsBroken2','dfdfs'
Select 1234,1234,'AFAccountUpdate1','Arrangements','addf','Test1','dfsdff'
so basically we have to pivot and dynamic sql and insert the expected output to a common table which will have all the required fields
Thanks,Ram.
Please don't forget to Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful. It will helpful to other users.This should give you what you're looking for
SELECT N9_Router_Account_Number,TC_Debt_Item_Reference,PageName,
MAX(CASE WHEN SEQ = 1 THEN fieldname END) AS fieldname1,
MAX(CASE WHEN SEQ = 1 THEN fieldvalue END) AS fieldvalue1,
MAX(CASE WHEN SEQ = 2 THEN fieldname END) AS fieldname2,
MAX(CASE WHEN SEQ = 2 THEN fieldvalue END) AS fieldvalue2,
MAX(CASE WHEN SEQ = 3 THEN fieldname END) AS fieldname3,
MAX(CASE WHEN SEQ = 3 THEN fieldvalue END) AS fieldvalue3,
MAX(CASE WHEN SEQ = 4 THEN fieldname END) AS fieldname4,
MAX(CASE WHEN SEQ = 4 THEN fieldvalue END) AS fieldvalue4
FROM
SELECT *,ROW_NUMBER() OVER (PARTITION BY N9_Router_Account_Number,TC_Debt_Item_Reference,PageName ORDER BY PageName) AS SEQ,*
FROM test_pivot_dynamic
)t
GROUP BY N9_Router_Account_Number,TC_Debt_Item_Reference,PageName
To make it dynamic see
http://www.beyondrelational.com/modules/2/blogs/70/posts/10791/dynamic-crosstab-with-multiple-pivot-columns.aspx
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Stored Procedures and Dynamic SQL
In order to return query results from a PL/SQL procedure, I currently use an IN OUT parameter to return a cursor to JDBC.
(Q: Is there any other way ???)
But if I want to use dynamic SQL (DBMS_SQL) within the procedure, I don't know how to return the results. How do I get a handle on the DBMS_SQL underlying cursor, rather than just its cursor-ID?
Can anyone help ?
Thanks,
Rob
([email protected])Very happy customer here!
-
So I have a chunk of data that only resides in Oracle. So I need to capture that information from Oracle. Now before you get over zealous, I did try with an OPENQUERY and it took FOREVER! And I don't know why the OPENQUERY took FOREVER but if I run the same
query directly against Oracle it runs very quickly...like 20 seconds.
So now I'm wondering...can I build a dataset in my SSRS Report that uses an Oracle Data source and an Oracle Stored Procedure in its Dataset that I'll create to aggregate this subset of data and then utilize its result set back in my main reporting
Dataset that will utilize SQL Server? And how can I do that? Can I make my main Dataset reference, say, a #TemporaryTable that is created from my Oracle Dataset in its
I'll continue to Google a few things as I await your review and hopefully a reply.
Thanks in advance for your help.Hi ITBobbyP,
According to your description you want to use data from a Oracle data source into a DataSet which retrieving data from SQL Server. Right?
In Reporting Services, we can have multiple data sources in one project pointing to different database. And we can use separated dataset to retrieve data from different data source. However, it's not supported to combine the two datasets together
directly. We can only use Lookup(), LookupSet() function to combine fields from different dataset into one tablix when there are common columns between two datasets. This is the only way to make tow result sets together in SSRS.
Reference:
Lookup Function (Report Builder and SSRS)
LookupSet Function (Report Builder and SSRS)
Best Regards,
Simon Hou
TechNet Community Support -
Sql Server Stored Procedures Dynamic Parameters
<p>Hi All,</p><p>Please can anyone post a example for SQL Server 2005 Stored Procedure using Dynamic Parameters in Crystal Reports XI.</p><p>Thanks</p><p>Rahul </p><p> </p>
search notes for samples
Maybe you are looking for
-
Unconfirmed line items of a sales order into account in credit management
Hi Gurus Updated the customer orders via prog. RVKRED09. There is only one open order for this customer = 720662. My question is: in the credit master the sales value/credit exposure is USD 77.100,00. The order is for USD 105,900.00 . Found out that
-
Hello All, I am stuck up with ABAP Dump - DBIF_RSQL_ERROR. In my code i am fetching data from database tables ZOMLT and ZOMLG. The main objective being delete the orphan entries available in ZOMLT. (ZOMLT and ZOMLG have 5 primary keys in common) Step
-
Keynote - The font Calibri is missing. Your text might look different.
Since updating Keynote app, I keep getting the following message every time I open my presentation...even when I have made other changes: Some changes were made to your presentation. The font Calibri is missing. Your text might look different. With
-
We are creating forms and right now when we open the completed form in Adobe Reader, it gives us the message that we can not save the "changed" document, meaning the parts that have been filled in. We need to know how we can change the security setti
-
An error has occured while connecting to Airplay device
Hello I have the following setup Microsoft Windows 7 home premium SP1 Itunes 10.7.0.21 airport express ver 7.6.1 Airport Utility ver 5.6.1 I have a wifi Router which is used for the wireless network. Thus the airport only joins that network, and