Execute set of ddl scripts in pl/sql
Hello,
If I use DBMS_METADATA.GET_DDL and DBMS_METADATA.GET_GRANTED_DDL for a particular user I can get something like this:
CREATE USER "USERB" IDENTIFIED BY VALUES 'B6C9E444D14CDE5B' DEFAULT TABLESPACE "PROD_TBSP_03" TEMPORARY TABLESPACE "TEMP";
GRANT "SELECT_CATALOG_ROLE" TO "USERB";
GRANT "SCHEMA_ROLE" TO "USERB";
Now, how do I go executing this in pl/sql? The following would fail as execute immediate wouldn't run all of these at the same time:
DECLARE
v_str VARCHAR2(4000 BYTE);
BEGIN
v_str := 'CREATE USER "USERB" IDENTIFIED BY VALUES ''B6C9E444D14CDE5B'' DEFAULT TABLESPACE "PROD_TBSP_03" TEMPORARY TABLESPACE "TEMP";'
|| chr(10) || 'GRANT "SELECT_CATALOG_ROLE" TO "USERB";'
|| chr(10) || 'GRANT "SCHEMA_ROLE" TO "USERB";';
dbms_output.put_line(v_str);
EXECUTE IMMEDIATE v_str;
EXCEPTION
WHEN OTHERS
THEN
dbms_output.put_line('Exception encountered: '||SQLCODE||' - Error message: '||substr(SQLERRM,1,200));
END;
Any ideas on how to run it?
Thanks guys
Leo
v$version:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
PL/SQL Release 10.2.0.4.0 - Production
CORE 10.2.0.4.0 Production
TNS for Linux: Version 10.2.0.4.0 - Production
NLSRTL Version 10.2.0.4.0 - Production
Edited by: leocoppens on May 22, 2013 2:43 PM
DECLARE
v_str VARCHAR2(4000 BYTE);
BEGIN
v_str := 'CREATE USER "USERB" IDENTIFIED BY VALUES ''B6C9E444D14CDE5B'' DEFAULT TABLESPACE "PROD_TBSP_03" TEMPORARY TABLESPACE "TEMP";';
dbms_output.put_line(v_str);
EXECUTE IMMEDIATE v_str;
v_str := 'GRANT "SELECT_CATALOG_ROLE" TO "USERB";'
dbms_output.put_line(v_str);
EXECUTE IMMEDIATE v_str;
v_str := 'GRANT "SCHEMA_ROLE" TO "USERB";';
dbms_output.put_line(v_str);
EXECUTE IMMEDIATE v_str;
END;
/You should make sure you really want to do this, though. I don't think this style (ie dynamically running DBA tasks) is a generally accepted "good" practice :)
It's prone to a lot of issues - security and otherwise. Caution is advised.
Similar Messages
-
How to execute sets of DDL Statements in 1 command?
Hi All,
I've been trying to look for a way to run a set of DDL statements. I normally have text files with DDL Statements on it. So what I do is load the contents of this text file into a Textbox and then set the Textbox.Text as the CommandText of my command object. Unfortunately I get errors.
Here's my code...
Private Sub btnLoadFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim OpenDiag As New OpenFileDialog
Dim txtReader As StreamReader
OpenDiag.ShowDialog()
If OpenDiag.FileName <> "" Then
txtReader = File.OpenText(OpenDiag.FileName)
CommandTextBox.Text = txtReader.ReadToEnd
End If
End Sub
Private Sub btnExecute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim myConn As New OracleConnection(My.Settings.ConnectionString)
Dim myComm As New OracleCommand(CommandTextBox.Text, myConn)
Try
myConn.Open()
myComm.ExecuteNonQuery()
myConn.Close()
Catch ex As OracleException
MessageBox.Show(ex.Code & ": " & ex.Message)
End Try
End SubThe errors that I get are
"ORA-00900: Invalid SQL Statement"
- Not sure how I get this but I noticed that if i had remarks/comments in my text file, this is the error that i get. Although i don't get this error if i execute in SQL Plus.
"ORA-00911: Invalid Character"
- after removing the remarks/comments, i get this error. i tried removing the semi-colon ";" then it works okay if i'm running 1 DDL statement in my file.. but if i my file contains to DDL statements for example, then i get the this error "ORA-00922: Missing or Invalid Options".
can anyone help me with this?
thanks.yes. i have BEGIN and END in their corresponding places.
i found out that removing linefeeds and semi-colons somehow fixes the problem for DDL statements. also, if i use a RichTextBox and uses its RichTextBox.LoadFile(filename, RichTextBoxStreamType.PlainText) instead of the File.OpenText(filename), it works fine as well. although its not something i would want. so what i did was to create a PL/SQL Anonymous Block instead. this too works if i use a RichTextBox.LoadFile instead of a textbox. but i'm using these controls to see the contents. eventually i will need to use a variable to store the contents of the file and i'm worried that it won't work with it.
unfortunately it doesn't work when i use a string. i'm guessing because of the linefeeds and semi-colons are still there. -
Execute a unix shell script from forms9i
Hi ,
I would like to execute a unix shell script form a form when they pressed a button. The forms server is on Linux machine. I tried but when I pressed the button nothings happen. Could some one please help me how I could get working.
Is there is a way I could execute the unix shell script from PL/SQL proceudre or package.
Please some one help me.
BainYou would not expect to see anything happening because the
script cannot directly send output to the web form. However, you can get it to write output to a file and use web.show_document in the form after the host command to display the file and see the output. -
Executing Shell Scripts through PL-SQL
Hi All,
I am trying to execute a shell script from PL-SQL but I am not getting it right .
the code i used is as follows
----JAVA CLASS ---
CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "Host" AS
import java.io.*;
public class Host {
public static void executeCommand(String command) {
try {
String[] finalCommand;
if (isWindows()) {
finalCommand = new String[4];
// Use the appropriate path for your windows version.
finalCommand[0] = "C:\\windows\\system32\\cmd.exe"; // Windows XP/2003
//finalCommand[0] = "C:\\winnt\\system32\\cmd.exe"; // Windows NT/2000
finalCommand[1] = "/y";
finalCommand[2] = "/c";
finalCommand[3] = command;
else {
finalCommand = new String[3];
finalCommand[0] = "/bin/sh";
finalCommand[1] = "-c";
finalCommand[2] = command;
final Process pr = Runtime.getRuntime().exec(finalCommand);
pr.waitFor();
new Thread(new Runnable(){
public void run() {
BufferedReader br_in = null;
try {
br_in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String buff = null;
while ((buff = br_in.readLine()) != null) {
System.out.println("Process out :" + buff);
try {Thread.sleep(100); } catch(Exception e) {}
br_in.close();
catch (IOException ioe) {
System.out.println("Exception caught printing process output.");
ioe.printStackTrace();
finally {
try {
br_in.close();
} catch (Exception ex) {}
}).start();
new Thread(new Runnable(){
public void run() {
BufferedReader br_err = null;
try {
br_err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String buff = null;
while ((buff = br_err.readLine()) != null) {
System.out.println("Process err :" + buff);
try {Thread.sleep(100); } catch(Exception e) {}
br_err.close();
catch (IOException ioe) {
System.out.println("Exception caught printing process error.");
ioe.printStackTrace();
finally {
try {
br_err.close();
} catch (Exception ex) {}
}).start();
catch (Exception ex) {
System.out.println(ex.getLocalizedMessage());
public static boolean isWindows() {
if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1)
return true;
else
return false;
---PROCEDURE TO BE EXECUTED WHICH USES THE ABOVE JAVA CLASS IS ----
CREATE OR REPLACE PROCEDURE Host_Command (p_command IN VARCHAR2)
AS LANGUAGE JAVA
NAME 'Host.executeCommand (java.lang.String)';
--- THE PERMISSIONS ---
call dbms_java.grant_permission('SYSTEM', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete');
call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
--- THE SHELL SCRIPT IS -----
#!/bin/sh
# This script removes the carriage returns from the Files having .DAT1 extensions in the /test/ Directory
# and the sends the single line stream to the new file with the use of 'gawk' command
# so finaly the files with same primary name but different secondary name are created
# e.g. file 'test.DAT1' is onverted to 'test.DAT'
# LOOP on /test/ DIRECTORY FOR SEARCHING FILES HAVING EXTENSION *.DAT1
for file_name in `ls /test/*.DAT1`
do
new_file_name=`echo $file_name | sed 's/DAT1/DAT/'`
# SEND THE CONTAINTS OF SELECTED FILE IN LOOP AS A CONTINUOUS STREAM TO NEW FILE NAME USING 'gawk' COMMAND
gawk 'BEGIN { ORS = "''" } { print $0 }' $file_name >> $new_file_name
# ABOVE LINE WILL CREATE A NEW FILE WITH SAME PRIMARY NAME BUT .DAT AS SECONDARY NAME(EXTENSION)
# REMOVE THE PRIOR FILE(s) AFTER SUCCESSFUL CALL TO 'gawk'
# $? returns 0 if the call to gawk command is succesfull
if test 0 = "$?"
then
rm -f $file_name
fi
done
# END LOOP ON /test/ DIRECTORY
---THE CALL TO THE PROCEDURE --
SQL>CALL DBMS_JAVA.SET_OUTPUT(1000000);
SQL>SET SERVEROUTPUT ON SIZE 1000000
SQL>exec host('/root/sh ecs_script.sh'); -----------------------------------------------1
now, the statement 1 is the path of the Shell Script ecs_script.sh
which uses gawk command and does some operations on some file..
but when i give the call in Statement 1 its giving error like
/bin/sh is not a directory
so i am not getting wHat should I do so that my script "ecs_script.sh" gets executed..
Please Help.The Java proc says:
> finalCommand[0] = "/bin/sh";
finalCommand[1] = "-c";
finalCommand[2] = command;
You call it as follows:
SQL>exec host('/root/sh ecs_script.sh');
The final command will be:
/bin/sh -c /root/sh ecs_script.sh
Is this what you intended? -
Set maximum server memory by using sql scripts
Dear all
How to set maximum server memory by using sql scripts in sql server 2014? Thx a lot
Best regards,
WallaceYou can use
sys.Sp_Configure to set max server memory
Here are some recommendation for Max Server memory based on RAM size
GB
MB
Recommended Setting
Command
16
16384
14745
EXEC sys.sp_configure 'max server memory (MB)', '14745'; RECONFIGURE;
32
32768
29491
EXEC sys.sp_configure 'max server memory (MB)', '29491'; RECONFIGURE;
64
65536
58982
EXEC sys.sp_configure 'max server memory (MB)', '58982'; RECONFIGURE;
128
131072
117964
EXEC sys.sp_configure 'max server memory (MB)', '117964'; RECONFIGURE;
256
262144
235929
EXEC sys.sp_configure 'max server memory (MB)', '235929'; RECONFIGURE;
512
524288
471859
EXEC sys.sp_configure 'max server memory (MB)', '471859'; RECONFIGURE;
1024
1048576
943718
EXEC sys.sp_configure 'max server memory (MB)', '943718'; RECONFIGURE;
2048
2097152
1887436
EXEC sys.sp_configure 'max server memory (MB)', '1887436'; RECONFIGURE;
4096
4194304
3774873
EXEC sys.sp_configure'max server memory (MB)', '3774873'; RECONFIGURE;
Hope this will help
Glad to help! Please remember to accept the answer if you found it helpful. It will be useful for future readers having same issue. -
Executing ddl statment in pl/sql block
Hi all,
could anyone pls help in method for executing ddl statment in pl/sql block other than 'execute immediate' ?could anyone pls help in method for executing ddl statment in pl/sql block other than 'execute immediate' ?On newer db versions you have more options:
SQL> desc t
Error: object t does not exist
SQL> exec sys.dbms_prvtaqim.execute_stmt('create table michael.t (a integer)')
PL/SQL procedure successfully completed.
SQL> desc t
TABLE t
Name Null? Type
A NUMBER
SQL> exec sys.dbms_utility.exec_ddl_statement('drop table michael.t')
PL/SQL procedure successfully completed.
SQL> desc t
Error: object t does not exist;) -
Where can I get SQL DDL script repository?
Hello;
Do you know where I can get the huge SQL DDL script repository?
Thanks;
OrnsiriHi,
Welcome , you can use dbms_metadata.get_ddl to get the Script.
Example
select dbms_metadata.get_ddl('TABLE','DEPT','SCOTT') from dual;
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1794096300346327738
thanks -
Howto create SQL DDL script using kodo 3?
How do I create a SQL script (DDL script) for my database using kodo 3?
I've looked everywhere and can't figure it out :-(
The deprecated/replaced schematool had an outputfile option that did the
trick.
However, there seems to be no such option for the new mappingtool?
Thanks
JesperJesper Ladegaard wrote:
How do I create a SQL script (DDL script) for my database using kodo 3?
I've looked everywhere and can't figure it out :-(
The deprecated/replaced schematool had an outputfile option that did the
trick.
However, there seems to be no such option for the new mappingtool?
Thanks
JesperI think it works:
java kodo.jdbc.schema.SchemaTool -file ddl.sql -a createDB
or
java kodo.jdbc.schema.SchemaTool -file ddl.sql -a dropDB
Regards,
Vladimiras -
Running sql script from pl/sql
Is there any standard way to run an external sql script from pl/sql
I really appreciate any assistance.If you want, I did start writing a function reading and executing statements out of sql script with utl_file.
can I issue this command in PL/SQL: EXECUTE IMMEDIATE '@filename.sql';
the function could be extended for DDL, session setting, etc...
Regards
Laurent -
Problem downloading the ddl script
Hi all,
I am trying to upload a DDL script to execute it on my new apex application.
It doesn't work, I get an error, I realised that I have to copy and past the code of the creation of a table one by one.
Do you have any idea how to fix that ? to execute the ddl script at once ?
I cannot execute hundreds of queries one by one
Thank you, it is urgentMoun wrote:
Hi all,
I am trying to upload a DDL script to execute it on my new apex application.
It doesn't work, I get an error, I realised that I have to copy and past the code of the creation of a table one by one.
Do you have any idea how to fix that ? to execute the ddl script at once ?
I cannot execute hundreds of queries one by one
Thank you, it is urgentYour problems are no more or less "urgent" than any others on this forum, and the volunteers here are free to use their time as they see fit. Making claims of "urgency" is the best way to get your question ignored.
However in this case the problem is quite simple: you have not bothered to consult the documentation. Use the SQL Workshop SQL Scripts page. -
Conversion of SQL Server 2005 script to PL/SQL
I want to conver the below script into PL/SQL
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AuditLog]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[AuditLog](
[GroupID] [int] NOT NULL,
[ID] [int] NOT NULL,
[TableName] [varchar](25) NOT NULL,
[FieldName] [varchar](25) NOT NULL,
[FieldType] [varchar](25) NULL,
[OldValue] [text] NOT NULL,
[NewValue] [text] NOT NULL,
[ChangedOn] [timestamp] NOT NULL,
[ChangedBy] [int] NOT NULL,
CONSTRAINT [PK_AuditLog_ID] UNIQUE NONCLUSTERED
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UserRights]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[UserRights](
[UserID] [int] NULL,
[MenuName] [varchar](25) NULL,
[IsEnabled] [int] NULL,
CONSTRAINT [PK_UserRights_UserID] UNIQUE NONCLUSTERED
[UserID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GradeMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[GradeMaster](
[ID] [int] NULL,
[Name] [varchar](25) NULL,
[Description] [varchar](25) NULL,
[From] [float] NULL,
[To] [float] NULL,
CONSTRAINT [PK_GradeMaster_ID] UNIQUE NONCLUSTERED
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CostGroup]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[CostGroup](
[ID] [int] NOT NULL,
[Name] [varchar](25) NOT NULL,
CONSTRAINT [PK_CostGroup_ID] UNIQUE NONCLUSTERED
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ToIndex]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
** Function dbo.ToIndex
CREATE FUNCTION [dbo].[ToIndex](@string_to_index VARCHAR(1024))
RETURNS VARCHAR(1024)
AS
BEGIN
DECLARE @temp VARCHAR(1024)
DECLARE @ivar VARCHAR(1024)
DECLARE @tmps VARCHAR(1)
SET @temp = ''''
SET @ivar = UPPER(@string_to_index)
DECLARE @i INTEGER
SET @i = 1
WHILE (@i <= LEN(@string_to_index))
BEGIN
SET @tmps = SUBSTRING(@ivar, @i, 1)
IF (ASCII(@tmps) >= 48 AND ASCII(@tmps) <= 57) OR (ASCII(@tmps) >= 65 AND ASCII(@tmps) <= 90)
BEGIN
SET @temp = @temp + @tmps
END
SET @i = @i + 1
END
RETURN @temp
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MasterID]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[MasterID](
[TableID] [int] NOT NULL,
[TableName] [varchar](25) NOT NULL,
[NextID] [int] NULL DEFAULT ((1)),
CONSTRAINT [PK_MasterID_TableID] UNIQUE NONCLUSTERED
[TableID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UserList]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[UserList](
[ID] [int] NOT NULL,
[Name] [varchar](25) NOT NULL,
[Password] [varchar](25) NOT NULL,
[FullName] [varchar](25) NULL,
CONSTRAINT [PK_UserList_ID] UNIQUE NONCLUSTERED
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Product]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Product](
[GroupID] [int] NOT NULL,
[ID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,
[GrossMargin] [float] NULL DEFAULT ((0)),
[RMC] [float] NULL DEFAULT ((0)),
[Packing] [float] NULL DEFAULT ((0)),
[Overhead] [float] NULL DEFAULT ((0)),
[Others] [float] NULL DEFAULT ((0)),
[TotalCost] [float] NULL DEFAULT ((0)),
[DPRate] [float] NULL DEFAULT ((0)),
[CreatedOn] [datetime] NULL DEFAULT (getdate()),
[CreatedBy] [int] NULL DEFAULT ((1)),
[UpdatedOn] [datetime] NULL DEFAULT (getdate()),
[UpdatedBy] [int] NULL DEFAULT ((1)),
CONSTRAINT [PK_Product_GroupID_ID] UNIQUE NONCLUSTERED
[GroupID] ASC,
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RawMaterial]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RawMaterial](
[GroupID] [int] NOT NULL,
[ID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,
[CurPrice] [float] NULL,
[OldPrice] [float] NULL,
[CreatedOn] [datetime] NULL,
[CreatedBy] [int] NULL,
[UpdatedOn] [datetime] NULL,
[UpdatedBy] [int] NULL,
CONSTRAINT [PK_RawMaterial_GroupID_ID] UNIQUE NONCLUSTERED
[GroupID] ASC,
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Recipe]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Recipe](
[GroupID] [int] NOT NULL,
[ID] [int] NOT NULL,
[WEFDate] [datetime] NOT NULL,
[ProductID] [int] NOT NULL,
[RawMaterialID] [int] NOT NULL,
[Seq] [int] NOT NULL,
[Quantity] [float] NOT NULL,
[RMCost] [float] NOT NULL,
[CreatedOn] [datetime] NULL,
[CreatedBy] [int] NULL,
[UpdatedOn] [datetime] NULL,
[UpdatedBy] [int] NULL,
CONSTRAINT [PK_Recipe_GroupID_Seq_ProductID_RawMaterialID] UNIQUE NONCLUSTERED
[GroupID] ASC,
[Seq] ASC,
[ProductID] ASC,
[RawMaterialID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCalcGM]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author: Mohammed Haris
-- Create date: 24-12-2006
-- Description: RMC Calculator
-- =============================================
CREATE PROCEDURE [dbo].[spCalcGM]
-- Add the parameters for the function here
@GroupID int,
@ProductID int,
@RM_ID int,
@Price int = 0
AS
BEGIN
--SET NOCOUNT ON
-- Declare the return variable here
DECLARE @Result float
DECLARE @SumCurPrice0 float
DECLARE @SumCurPrice float
DECLARE @SumOldPrice float
DECLARE @SumQuantity float
DECLARE @SumRMC float
DECLARE @PTotalCost float
DECLARE @PDPRate float
-- Add the T-SQL statements to compute the return value here
SELECT @SumCurPrice0 = SUM(Recipe.Quantity * RawMaterial.CurPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID <> @RM_ID)
AND (Recipe.GroupID = @GroupID)
/*IF ISNULL(@SumCurPrice0)*/
SET @SumCurPrice = ISNULL(@SumCurPrice0, 0)
/*ELSE
SET @SumCurPrice = @SumCurPrice0*/
IF @Price = 0
SELECT @SumOldPrice = SUM(Recipe.Quantity * RawMaterial.CurPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID = @RM_ID)
AND (Recipe.GroupID = @GroupID)
ELSE
SELECT @SumOldPrice = SUM(Recipe.Quantity * RawMaterial.OldPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID = @RM_ID)
AND (Recipe.GroupID = @GroupID)
SELECT @SumQuantity = SUM(Recipe.Quantity)
FROM Recipe
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.GroupID = @GroupID)
SELECT @SumRMC = (@SumCurPrice + @SumOldPrice) / @SumQuantity
SELECT @PTotalCost = (Product.Packing + Product.Overhead + Product.Others),
@PDPRate = Product.DPRate
FROM Product
WHERE (Product.ID = @ProductID) AND (Product.GroupID = @GroupID)
SELECT @PTotalCost = @PTotalCost + @SumRMC
SELECT @Result = (@PDPRate - @PTotalCost) / @PDPRate
SELECT
@SumCurPrice0 AS SumCurPrice0,
@SumCurPrice AS SumCurPrice,
@SumOldPrice AS SumOldPrice,
@SumQuantity AS SumQuantity,
@SumRMC AS SumRMC
-- Return the result of the function
RETURN @Result
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_UpdateTotalCostAndGMForAllProducts]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE
[dbo].[sp_UpdateTotalCostAndGMForAllProducts]
AS
BEGIN
UPDATE Product
SET Product.TotalCost = Product.RMC + Product.Packing + Product.Overhead + Product.Others
UPDATE Product
SET Product.GrossMargin = (Product.DPRate - Product.TotalCost) / Product.DPRate
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_UpdateTotalCostAndGMForProduct]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE
[dbo].[sp_UpdateTotalCostAndGMForProduct] (@ProductID int)
AS
BEGIN
UPDATE Product
SET Product.TotalCost = Product.RMC + Product.Packing + Product.Overhead + Product.Others
WHERE Product.ID = @ProductID
UPDATE Product
SET Product.GrossMargin = (Product.DPRate - Product.TotalCost) / Product.TotalCost
WHERE Product.ID = @ProductID
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CalcGM]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author: Mohammed Haris
-- Create date: 24-12-2006
-- Description: RMC Calculator
-- =============================================
CREATE FUNCTION [dbo].[CalcGM]
-- Add the parameters for the function here
@GroupID int,
@ProductID int,
@RM_ID int,
@Price int = 0
RETURNS float
AS
BEGIN
--SET NOCOUNT ON
-- Declare the return variable here
DECLARE @Result float
DECLARE @SumCurPrice float
DECLARE @SumOldPrice float
DECLARE @SumQuantity float
DECLARE @SumRMC float
DECLARE @PTotalCost float
DECLARE @PDPRate float
-- Add the T-SQL statements to compute the return value here
SELECT @SumCurPrice = SUM(Recipe.Quantity * RawMaterial.CurPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID <> @RM_ID)
AND (Recipe.GroupID = @GroupID)
SET @SumCurPrice = ISNULL(@SumCurPrice, 0)
IF @Price = 0
SELECT @SumOldPrice = SUM(Recipe.Quantity * RawMaterial.CurPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID = @RM_ID)
AND (Recipe.GroupID = @GroupID)
ELSE
SELECT @SumOldPrice = SUM(Recipe.Quantity * RawMaterial.OldPrice)
FROM RawMaterial INNER JOIN
Recipe ON RawMaterial.ID = Recipe.RawMaterialID
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.RawMaterialID = @RM_ID)
AND (Recipe.GroupID = @GroupID)
SELECT @SumQuantity = SUM(Recipe.Quantity)
FROM Recipe
WHERE (Recipe.ProductID = @ProductID)
AND (Recipe.GroupID = @GroupID)
SELECT @SumRMC = (@SumCurPrice + @SumOldPrice) / @SumQuantity
SELECT @PTotalCost = (Product.Packing + Product.Overhead + Product.Others),
@PDPRate = Product.DPRate
FROM Product
WHERE (Product.ID = @ProductID) AND (Product.GroupID = @GroupID)
SELECT @PTotalCost = @PTotalCost + @SumRMC
SELECT @Result = (@PDPRate - @PTotalCost) / @PDPRate
-- Return the result of the function
RETURN @Result
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_RMCostImplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_RMCostImplication]
@GroupID int = 1,
@RM_ID int = 1
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT Product.Name, Product.DPRate, RawMaterial.Name AS RMName,
RawMaterial.CurPrice,
dbo.CalcGM(@GroupID, Product.ID, @RM_ID, 0)*100 AS CurGM,
RawMaterial.OldPrice,
dbo.CalcGM(@GroupID, Product.ID, @RM_ID, 1)*100 AS OldGM
FROM Product INNER JOIN
Recipe ON Product.ID = Recipe.ProductID INNER JOIN
RawMaterial ON Recipe.RawMaterialID = RawMaterial.ID
WHERE (Product.GroupID = @GroupID) AND (RawMaterial.ID = @RM_ID)
ORDER BY Product.Name
END
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Product_GroupID]') AND parent_object_id = OBJECT_ID(N'[dbo].[Product]'))
ALTER TABLE [dbo].[Product] WITH CHECK ADD CONSTRAINT [FK_Product_GroupID] FOREIGN KEY([GroupID])
REFERENCES [dbo].[CostGroup] ([ID])
GO
ALTER TABLE [dbo].[Product] CHECK CONSTRAINT [FK_Product_GroupID]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_RawMaterial_GroupID]') AND parent_object_id = OBJECT_ID(N'[dbo].[RawMaterial]'))
ALTER TABLE [dbo].[RawMaterial] WITH CHECK ADD CONSTRAINT [FK_RawMaterial_GroupID] FOREIGN KEY([GroupID])
REFERENCES [dbo].[CostGroup] ([ID])
GO
ALTER TABLE [dbo].[RawMaterial] CHECK CONSTRAINT [FK_RawMaterial_GroupID]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Recipe_GroupID_ProductID]') AND parent_object_id = OBJECT_ID(N'[dbo].[Recipe]'))
ALTER TABLE [dbo].[Recipe] WITH CHECK ADD CONSTRAINT [FK_Recipe_GroupID_ProductID] FOREIGN KEY([GroupID], [ProductID])
REFERENCES [dbo].[Product] ([GroupID], [ID])
GO
ALTER TABLE [dbo].[Recipe] CHECK CONSTRAINT [FK_Recipe_GroupID_ProductID]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Recipe_GroupID_RawMaterialID]') AND parent_object_id = OBJECT_ID(N'[dbo].[Recipe]'))
ALTER TABLE [dbo].[Recipe] WITH CHECK ADD CONSTRAINT [FK_Recipe_GroupID_RawMaterialID] FOREIGN KEY([GroupID], [RawMaterialID])
REFERENCES [dbo].[RawMaterial] ([GroupID], [ID])
GO
ALTER TABLE [dbo].[Recipe] CHECK CONSTRAINT [FK_Recipe_GroupID_RawMaterialID]
Edited by: yogeshyl on Jul 28, 2009 4:50 PMDear yogeshyl!
OK, Let's try this step by step. I assume that you want to use Oracle in a version above 9i R2.
-- Please change the size x to a value that fits your needs. Every tablespace needs a datafile.
-- Please change <path_and_filename>.dbf to something like C:\oracle\oradata\ORCL\primary01.dbf.
CREATE TABLESPACE primary
DATAFILE '<path_and_filename>.dbf' SIZE x M;
CREATE USER object_owner
IDENTIFIED BY password
DEFAULT TABLESPACE primary
TEMPORARY TABLESPACE temp
QUOTA unlimited ON primary;
DROP TABLE object_owner.auditlog;
CREATE TABLE object_owner.auditlog
GroupID NUMBER NOT NULL,
ID NUMBER NOT NULL CONSTRAINT pk_auditlog_id PRIMARY KEY,
table_name VARCHAR2(25) NOT NULL,
field_name VARCHAR2(25) NOT NULL,
field_type VARCHAR2(25) NULL,
old_value VARCHAR2(4000) NOT NULL,
new_value VARCHAR2(4000) NOT NULL,
changed_on TIMESTAMP NOT NULL,
changed_by NUMBER NOT NULL
DROP TABLE object_owner.userrights;
CREATE TABLE object_owner.userrights
UserID NUMBER NULL CONSTRAINT pk_userrights_userid PRIMARY KEY,
MenuName VARCHAR2(25),
IsEnabled NUMBER
DROP TABLE object_owner.grademaster;
CREATE TABLE object_owner.grademaster
ID NUMBER NULL CONSTRAINT pk_grademaster_id PRIMARY KEY,
Name VARCHAR2(25),
Description VARCHAR2(25),
source NUMBER,
destination NUMBER
DROP TABLE object_owner.costgroup;
CREATE TABLE object_owner.costgroup(
ID NUMBER NOT NULL CONSTRAINT pk_costgroup_id PRIMARY KEY,
Name VARCHAR2(25) NOT NULL
DROP TABLE object_owner.masterid;
CREATE TABLE object_owner.masterid
TableID NUMBER NOT NULL CONSTRAINT pk_masterid_table_id PRIMARY KEY,
TableName VARCHAR2(25) NOT NULL,
NextID NUMBER DEFAULT ((1))
DROP TABLE object_owner.user_list;
CREATE TABLE object_owner.userlist
ID NUMBER NOT NULL CONSTRAINT pk_userlist_id PRIMARY KEY,
Name VARCHAR2(25) NOT NULL,
Password VARCHAR2(25) NOT NULL,
FullName VARCHAR2(25)
DROP TABLE object_owner.product;
CREATE TABLE dbo.Product
GroupID NUMBER NOT NULL,
ID NUMBER NOT NULL,
Name VARCHAR2(50) NOT NULL,
GrossMargin NUMBER DEFAULT ((0)),
RMC NUMBER DEFAULT ((0)),
Packing NUMBER DEFAULT ((0)),
Overhead NUMBER DEFAULT ((0)),
Others NUMBER DEFAULT ((0)),
TotalCost NUMBER DEFAULT ((0)),
DPRate NUMBER DEFAULT ((0)),
CreatedOn DATE DEFAULT SYSDATE,
CreatedBy NUMBER DEFAULT ((1)),
UpdatedOn DATE DEFAULT SYSDATE,
UpdatedBy NUMBER DEFAULT ((1)),
CONSTRAINT pk_product_groupid_id PRIMARY KEY (id, groupid);
DROP TABLE object_owner.rawmaterial;
CREATE TABLE object_owner.rawmaterial(
GroupID NUMBER NOT NULL,
ID NUMBER NOT NULL,
Name VARCHAR2(50) NOT NULL,
CurPrice NUMBER,
OldPrice NUMBER,
CreatedOn DATE,
CreatedBy NUMBER,
UpdatedOn DATE,
UpdatedBy NUMBER,
CONSTRAINT pk_rawmaterial_groupid_id PRIMARY KEY (groupid, id)
DROP TABLE object_owner.recipe;
CREATE TABLE object_owner.recipe
GroupID NUMBER NOT NULL,
ID NUMBER NOT NULL,
WEFDate DATE NOT NULL,
ProductID NUMBER NOT NULL,
RawMaterialID NUMBER NOT NULL,
Seq NUMBER NOT NULL,
Quantity NUMBER NOT NULL,
RMCost NUMBER NOT NULL,
CreatedOn DATE,
CreatedBy NUMBER,
UpdatedOn DATE,
UpdatedBy NUMBER,
CONSTRAINT pk_r_gid_pid_rawmaterial_id PRIMARY KEY (GroupID, Seq, productid, rawmaterialID)
CREATE OR REPLACE FUNCTION object_owner.to_index(p_string_to_index IN VARCHAR2) RETURN VARCHAR2
IS
l_temp VARCHAR2(1024);
l_ivar VARCHAR2(1024);
l_tmps VARCHAR2(1);
BEGIN
l_ivar := UPPER(p_string_to_index);
FOR i IN 1..LENGTH(p_string_to_index) LOOP
l_tmps := SUBSTR(l_ivar, i, 1);
IF ((ASCII(l_tmps) BETWEEN 48 AND 57) OR (ASCII(l_tmps) BETWEEN 65 AND 90)) THEN
l_temp := l_temp || l_tmps;
END IF;
END LOOP;
RETURN l_temp;
END;
ALTER TABLE object_owner.product
DROP CONSTRAINT fk_product_groupid;
ALTER TABLE object_owner.product
ADD CONSTRAINT fk_product_groupid FOREIGN KEY (groupid)
REFERENCES object_owner.costgroup(id);
ALTER TABLE object_owner.rawmaterial
DROP CONSTRAINT fk_rawmaterial_groupid;
ALTER TABLE object_owner.rawmaterial
ADD CONSTRAINT fk_rawmaterial_groupid FOREIGN KEY (groupid)
REFERENCES object_owner.costgroup(id);
ALTER TABLE object_owner.recipe
DROP CONSTRAINT fk_recipe_groupid_productid ;
ALTER TABLE object_owner.recipe
ADD CONSTRAINT fk_recipe_groupid_productid FOREIGN KEY (groupid, productid)
REFERENCES object_owner.product(groupid, id);
ALTER TABLE object_owner.recipe
DROP CONSTRAINT fk_recipe_groupid_rmatid;
ALTER TABLE object_owner.recipe
ADD CONSTRAINT fk_recipe_groupid_rmatid FOREIGN KEY (groupid, rawmaterialid)
REFERENCES object_owner.rawmaterial (groupid, id);Yours sincerely
Florian W.
Edited by: Florian W. on 28.07.2009 13:22
Edited by: Florian W. on 28.07.2009 13:29
Edited by: Florian W. on 28.07.2009 13:40
Edited by: Florian W. on 28.07.2009 13:58
Edited by: Florian W. on 28.07.2009 14:10
Edited by: Florian W. on 28.07.2009 14:21 -
How to view the DDL script prior to object deployment in OWB 10g R2?
How to view the DDL script prior to object deployment in OWB 10g R2?
Here is what I' looking for: in 10gR2, let's say I've built dimension X, but it's not deployed yet. I've selected one of the deployment options, let's say: "Deploy to Catalog only". Now, I'd like to see a DDL script that will be executed at the deployment time. Where can I find this script? What screen? What menu?
Thanks,
vrViewing the Scripts
After you have generated scripts for your target objects, you can open the scripts and
view the code. Warehouse Builder generates the following types of scripts:
■ DDL scripts: Creates or drops database objects.
■ SQL*Loader control files: Extracts and transports data from file sources.
■ ABAP scripts: Extracts and loads data from SAP systems.
To view the generated scripts:
1. From the Generation Results window, select an object in the navigation tree on the
left of the Generation Results dialog.
2. Select the Scripts tab on the right of this dialog.
The Scripts tab contains a list of the generated scripts for the object you selected.
3. Select a specific script and click the View Code button.
Regards,
Marcos -
Execute "set scan off" from vb 6.0 adodb connection
Hi,
We are trying to execute "set scan off" from vb - but it throws an error like missing or invalid option.
We also tried clubbing two statements like - "set scan off;insert into table_name values...;" but still the errr is same,
We are using adodb connection object's execute method.Rest all ddl and dml are working fine. Any help appreciated.P. Forstmann wrote:
I don't think you can run it from an OCI/ODBC/JDBC database session.No thinking required. Quite simply, you can't run SQL*Plus commands through an ODBC connection. -
DDL script in Oracle Scheduler
Hello,
Right now I have a DDL script and I would like to submit this script to the Oracle Scheduler under the Oracle Enterprise Manager (i'm using 10gR2). I tried using Program but it keeps saying some path error problem. I tried using PL/SQL but I don't know the code to execute the DDL script (so many lines that i can't copy and paste to the scheduler, but i have it in a seperate file). Can anyone help on this one?
Thanks,
GHHi,
two different way:
a) write a small shell-script around the sql script an execute the shell-script from the scheduler.
b) writh a pl/sql procedure which executes the ddl-statements using "execute immediate"
Torsten -
Generating ddl script in oracle
Hi ,
i ned a script to generate ddl's for all the objects in a particular schema.
i used the DBMS package dbms_metadata.get_ddl
SELECT 'select dbms_metadata.get_ddl('''||OBJECT_TYPE||''','''||OBJECT_NAME||''','''||OWNER||''') from dual;' FROM DBA_OBJECTS WHERE OWNER='RSEXT' AND OBJECT_TYPE='TABLE'
by using the above script i am not getting the complete script.
how can i get the complete script.
can anyone suggest me.
thanks in advance.Hi,
two different way:
a) write a small shell-script around the sql script an execute the shell-script from the scheduler.
b) writh a pl/sql procedure which executes the ddl-statements using "execute immediate"
Torsten
Maybe you are looking for
-
HT201302 How do I delete a photo from my camera roll and not delete it from a folder
When I delete photos from my camera roll, it also deletes them from the folder I've saved them in. How do I delete from the camera roll and not lose them from the folder?
-
I need a logic for the version management report
HI Here with sending my req. Please give me the posible solution,its urgent, 1. Get all the objects included in a transport request by using function module /DGN/ITC_TRANSPORT_TO_OBJECT. 2. Find the Objects which have the versions maintained
-
Hello, i would like to know how the paint(Graphics g, Shape allocation) method is working, especially how it gets the Shape object. I would like to reuse this Shape object in other method. My class subclass javax.swing.text.BoxView. thansk for help
-
Replacing the Java Code Signing Certificate on the ASA 55xx VPN/Firewall Appliance
Hi, basically I am trying to achieve what's documented in http://www.cisco.com/en/US/docs/security/asa/asa80/release/notes/asarn80.html#wp242704 (using ASDM: "crypto ca import" = Remote Access VPN -> Certificate Management -> Code Signer -> Import)
-
Unable to preview jpg tif files in Win 8 Explorer
Before installing Design Std CS6 (not CC) plus Acrobat XI Pro, I was able to preview jpg and tif files in Windows 8 Explorer in any of the views (XLg, Large, Medium icons) and in the Preview Pane. However, now I only see the program icon, regardless