PLS-00201: identifier 'IMMEDIATE' must be declared when using EXECUTE IMMEDIATE? - database

I'm trying to use execute immediate to create a table as follows :
EXECUTE IMMEDIATE (q'{CREATE TABLE ... ;}');
However oracle gives me the following error:
ORA-06550: line 1, column 7:
PLS-00201: identifier 'IMMEDIATE' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action:
how do i correctly format my string to create my table?

You cannot run ddl operation using dynamic sql with sqlplus.
Test case to replicate the error
SQL> EXECUTE IMMEDIATE (q'{CREATE TABLE test1000(id int,name varchar2(10)}');
BEGIN IMMEDIATE (q'{CREATE TABLE test1000(id int,name varchar2(10)}';); END;
*
ERROR at line 1:
ORA-06550: line 1, column 7:
PLS-00201: identifier 'IMMEDIATE' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Since it doesn't work in sqlplus let's switch to anonymous pl/sql block
SQL> BEGIN
2 EXECUTE IMMEDIATE (q'{CREATE TABLE test1000(id int,name varchar2(10));}');
3* END;
SQL> /
BEGIN
*
ERROR at line 1:
ORA-00922: missing or invalid option
ORA-06512: at line 2
Remove colon in curly brackets to avoid above error
SQL> BEGIN
2 EXECUTE IMMEDIATE (q'{CREATE TABLE test1000(id int,name varchar2(10))}');
3* END;
PL/SQL procedure successfully completed.
SQL> #ddl test1000
PL/SQL procedure successfully completed.
DBMS_METADATA.GET_DDL(OBJECT_TYPE,OBJECT_NAME,OWNER)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE TABLE "HR"."TEST1000"
( "ID" NUMBER(*,0),
"NAME" VARCHAR2(10) COLLATE "USING_NLS_COMP"
) DEFAULT COLLATION "USING_NLS_COMP" SEGMENT CREATION DEFERRED
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
NOCOMPRESS LOGGING
TABLESPACE "EXAMPLE" ;

Related

SQL Server function error with if condition

I'm still trying to learn an SQL, i made a mistakes but i already search on the internet about the if statements...
I tried to create a simple function to check if the parameter is match the condition..
I have 2 parameters, that will be inputted manually by the users, but i got an error saying
Msg 156, Level 15, State 1, Procedure ufn_calculatebonus, Line 4 [Batch Start Line 1] Incorrect syntax near the keyword 'IF'. Msg 178, Level 15, State 1, Procedure ufn_calculatebonus, Line 10 [Batch Start Line 1] A RETURN statement with a return value cannot be used in this context.
This is the code i've tried to create, i thought i make the IF condition right? After the IF , should have a BEGIN and statements, closing it with END. ??
CREATE FUNCTION Sales.ufn_calculatebonus (#CompanyRevenue int, #OptionalParameter varchar(60))
RETURNS TABLE
AS
IF #CompanyRevenue > 10
BEGIN
SELECT 'INPUT CANNOT BE BIGGER THAN 1000'
END
ELSE
BEGIN
RETURN
(
SELECT * FROM SALES.CUSTBALANCE2 where region=#OptionalParameter or name=#OptionalParameter
);
END
GO
There are 2 distinct types of T-SQL table-valued functions, inline TVF and multi-statement TVF. The body of an inline TVF consists of only of a RETURNS statement with a query specification (not to be confused with a RETURN statement).
Your attempt at a multi-statement table-valued function is invalid for the reasons below.
The body of a multi-statement TVF must be surrounded with BEGIN...END.
A table variable with the returned schema must be declared in the function header.
One cannot return query results with a RETURN statement. Instead, insert results into the table variable declared in the function header end specify RETURN at the end of the function to return the results.
Below is an example of the remediated code. Importantly, note the use of an explicit column list throughout. Don't SELECT * in production code.
CREATE OR ALTER FUNCTION dbo.ufn_calculatebonus (#CompanyRevenue int, #OptionalParameter varchar(60))
RETURNS #BalanceInfo TABLE (CustomerID int, Balance int, ErrorMessage varchar(100))
AS
BEGIN
IF #CompanyRevenue > 10
BEGIN
INSERT INTO #BalanceInfo (ErrorMessage) VALUES('INPUT CANNOT BE BIGGER THAN 1000');
END
ELSE
BEGIN
INSERT INTO #BalanceInfo (CustomerID, Balance) --note ErrorMessage is omitted and will be NULL
SELECT CustomerID, Balance FROM SALES.CUSTBALANCE2 where region=#OptionalParameter or name=#OptionalParameter;
END;
RETURN;
END
GO
A stored procedure is a better fit than a than user-defined function if you need to raise custom errors for parameter validation. Here's a stored procedure example:
CREATE OR ALTER PROCEDURE dbo.usp_calculatebonus (#CompanyRevenue int, #OptionalParameter varchar(60))
AS
IF #CompanyRevenue > 10
BEGIN
THROW 50000, 'INPUT CANNOT BE BIGGER THAN 1000', 16;
END;
SELECT CustomerID, Balance FROM SALES.CUSTBALANCE2 where region=#OptionalParameter or name=#OptionalParameter;
GO

SQL Server trigger does not recognize inserted row

I have simple SQL Server trigger and for some reason it does not recognize INSERTED row.
Here is code:
-- code
DROP TABLE a;
GO
CREATE TABLE a
(
id INT IDENTITY(1,1) PRIMARY KEY,
v INT
)
GO
DROP TABLE a_audit;
CREATE TABLE a_audit
(
id INT,
v INT,
[updated_at] [DATETIME] NOT NULL DEFAULT GETDATE()
)
GO
CREATE TRIGGER [dbo].[trg_a]
ON [dbo].[a]
AFTER INSERT, UPDATE, DELETE
NOT FOR REPLICATION
AS
BEGIN
SET NOCOUNT ON;
PRINT 'start';
DECLARE #xmltmp xml = (SELECT * FROM inserted FOR XML AUTO);
PRINT CONVERT(NVARCHAR(MAX), #xmltmp);
-- INSERT INTO a_audit (id, v) VALUES (inserted.id, inserted.v);
END;
GO
INSERT INTO a (v)
VALUES (1);
WAITFOR DELAY '00:00:01.11';
INSERT INTO a (v)
VALUES (2);
GO
SELECT * FROM a;
PRINT 'done'
It produces this output
start
<inserted id="1" v="1"/>
(1 row affected)
start
<inserted id="2" v="2"/>
(1 row affected)
(2 rows affected)
done
So I see that INSERTED row does exist.
However, if I remove comment on insert statements the output is this:
Msg 4104, Level 16, State 1, Procedure trg_a, Line 14 [Batch Start Line 16]
The multi-part identifier "inserted.id" could not be bound.
Msg 4104, Level 16, State 1, Procedure trg_a, Line 14 [Batch Start Line 16]
The multi-part identifier "inserted.v" could not be bound.
What is wrong?
inserted is a table, not a function. To INSERT from another table you need to use a INSERT INTO... SELECT ... FROM statement:
INSERT INTO a_audit (id,v)
SELECT id,
v
FROM inserted;
You can't reference a table's columns unless you use a FROM. For example just running the below would give the error below:
SELECT a_audit.id, a.audit.v;
The multi-part identifier "a_audit.id" could not be bound.
You would have to a SELECT...FROM:
SELECT id, v
FROM a_audit;

Calling stored procedure and save its results in a temporary table (error)

Trying to call a procedure and insert the results into a temp table:
CREATE TABLE #TempTable22
(
ChargeType Int,
ChargeCode varchar(250),
CarrierCode varchar(250),
Market varchar(250),
CurrencyCode varchar(250),
PaymentMethodCode varchar(250),
ForiegnCurrencyCode varchar(250),
ChargeAmount Float,
ForiengAmount Float,
MarketCharge varchar(250),
DirectRate Float,
ExcessBagCommisionRate Float
)
INSERT INT #TempTable22
EXEC [dbo].[Sp_AutoJV_SalesSummary_ForTest] #DateFrom, #DateTo, #CurrencyCode, #OrganizationCode, #OrgCurrencyCode, #LocationCode, #Market, #Sales, #PaymentMethodCode;
SELECT
ChargeType,
ChargeCode,
CarrierCode,
Market,
CurrencyCode,
PaymentMethodCode,
ForiegnCurrencyCode,
ChargeAmount,
ForiengAmount,
MarketCharge,
DirectRate,
ExcessBagCommisionRate,
0 * ExcessBagCommisionRate as Test
FROM
#TempTable22
Note: # when I call the stored procedure without inserting it there is no problem but when I add the insert into #TempTable22 the error will now prompt.
Full error
Msg 3930, Level 16, State 1, Procedure Sp_AutoJV_SalesSummary_GetChargeDetailsNoDGV2_ForTest, Line 46 [Batch
Start Line 73]
The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction.
Msg 208, Level 16, State 0, Procedure Sp_AutoJV_SalesSummary_GetChargeDetailsNoDGV2_ForTest, Line 835 [Batch
Start Line 73]
Invalid object name '#Stations'.
Msg 3930, Level 16, State 1, Procedure Sp_AutoJV_SalesSummary_Report_ForTest2, Line 63 [Batch Start Line 73]
The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction. (0 row(s) affected)
You need to create Table valued function to be able to use it in an select or insert statement. Please see below link
When would you use a table-valued function?

Implementing IF statement on Oracle Database

Im trying to implement an IF statement to run a query on my Oracle Database.
The expectation:
If the employee is called John, display the limited items(item1 and item2), if it's not John, display the complete list.
DECLARE
employeeName STRING := 'John';
BEGIN
IF (employeeName = 'John') THEN
       (SELECT TableA.Table from Table where TableA.Table = 'Item1' OR TableA.Table = 'Item2');
ELSE 
       (SELECT TableA.Table from Table);
END IF;
END;
Here's the error output:
Error report: ORA-06550: line 6, column 2: PLS-00103: Encountered the symbol " " when expecting one of the following:
( begin case declare exit for goto if loop mod null pragma raise
return select update while with 'an identifier' 'a double-quoted
delimited-identifier' 'a bind variable' ""continue close current
delete fetch lock insert open rollback savepoint set sql execute
commit forall merge pipe purge
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action:
What am I doing wrong? Forgive my ignorance on IF statements implemented on databases.
In your code,
table is a reserved keyword. Use double quotes or a different identifier
select is missing into.
String is missing length
You can apply your condition in a single SQL and then, use a for loop to loop over the result set.
DECLARE
employeeName varchar2(100) := 'John';
BEGIN
for t in (select "table" from tablea
where "table" in ('item1', 'item2')
or employeename = 'john') loop
dbms_output.put_line(t."table");
end loop;
END;
/

PLS-00201 Error when running stored procedure in Oracle

I Recently moved on oracle database for one of my project. I have created a stored procedure for selecting multiple rows from database. Following is my procedure
create Or replace
PROCEDURE TEST(p_cursor OUT SYS_REFCURSOR) AS
BEGIN
open p_cursor FOR select * from branch_info;
END TEST;
when I execute this procedure I got following error:
*
ERROR at line 1:
ORA-06550: line 1, column 7:
PLS-00201: identifier 'SAURAV.TEST' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
I have searched for it and found similar question here but error line and reason are different.
Anyone please help me in solving this.
EDIT: Misprint TEST with TEXT
The problem is with keyword test
CREATE OR REPLACE PROCEDURE test (p_cursor OUT sys_refcursor)
AS
BEGIN
OPEN p_cursor FOR
SELECT *
FROM branch_info;
END test;
and execute by
variable rc refcursor;
exec test( :rc );
print rc;
ORA-06550: line 1, column 7:
PLS-00201: identifier 'TEST' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Change to some other name
CREATE OR REPLACE PROCEDURE test2 (p_cursor OUT sys_refcursor)
AS
BEGIN
OPEN p_cursor FOR
SELECT *
FROM branch_info;
END test2 ;
execute as
variable rc refcursor;
exec test2 ( :rc );
print rc;
PL/SQL procedure successfully completed.
From sql plus
SQL> variable usercur refcursor;
SQL> DECLARE
2 BEGIN
3 test2(:usercur);
4 end;
5 /
PL/SQL procedure successfully completed.
SQL> print usercur;

Resources