Defining a schema inside a procedure - sql

I'm working on creating a model data base design for a retail store. I'm trying to create a single procedure which will initialize the database schema.
What I'm trying to achieve is to create a new schema from inside the procedure. My code is as follows:
begin trans
create procedure Retail_Fill
as
create schema Retail_Test;
go
create table Retail_Test.customer(
cust_id int,
cust_name varchar(30),
cust_phone int,
cust_add varchar(50),
constraint pk_customer primary key (cust_id)
);
Here the create schema statement works fine by itself. But inside the procedure it gives an error:
Invaid Syntax!CREATE SCHEMA must be the only statement in the batch
I want to know if it is at all possible to achieve this. If yes then what am I doing wrong or where is the error?

CREATE SCHEMA has to be executed as a separate batch. Batches in SQL Server Management Studio is separated by GO. That is not the case in a stored procedure. You can do what you want by using EXECUTE for the statements that needs to be in a batch of its own like CREATE SCHEMA or CREATE PROCEDURE.
create procedure Retail_Fill
as
exec('create schema Retail_Test');
create table Retail_Test.customer(
cust_id int,
cust_name varchar(30),
cust_phone int,
cust_add varchar(50),
constraint pk_customer primary key (cust_id)
);

As Mikael Eriksson said above creating DB Schema should be in a single script file or may be you can configure some deployment that will create your schema. So it will be good to avoid creating schema within procedures.
You can have these inside procedure when you have to design the schema on fly for each customer (for example).

Related

SQLDeveloper - Error on running statement but running script works fine?

In the SQLDeveloper software, there is a feature to run either a statement within a script or the entire script.
My issue is that my SQL Script works fine when I run the entire script, but throws a ORA-00955: name is already used by an existing object error when I try to run a single statement.
For example my script is as follows:
DROP TABLE "Movie" CASCADE CONSTRAINTS;
DROP TABLE "Critic" CASCADE CONSTRAINTS;
DROP TABLE "Review" CASCADE CONSTRAINTS;
CREATE TABLE "Critic" (
"cID" int NOT NULL, /* Since a review cannot have no critics*/
"CriticName" varchar(100),
"PhoneNumber" varchar(10),
PRIMARY KEY ("cID")
);
CREATE TABLE "Movie" (
"mID" int,
"Title" varchar(255),
"ReleaseDate" DATE,
"Rating" int,
"RunningTime" INTEGER, /*To store the duration of the film in minutes*/
"Director" varchar(100),
"Actor(s)" int,
PRIMARY KEY ("mID")
);
CREATE TABLE "Review" (
"rID" int,
"mID" int,
FOREIGN KEY ("mID") REFERENCES "Movie"("mID"),
"cID" int,
FOREIGN KEY ("cID") REFERENCES "Critic"("cID"),
"Rating" int,
PRIMARY KEY ("rID")
Why would this script run fine as a whole but fail if I try to run just one statement?
For reference, the feature I'm talking about looks like this in the GUI:
Figured it out due to #Gordon Linoff 's explanation.
The drop table command must be run before creating the table. And since the run statement command only runs a single statement, the drop command is never called, causing the error.
To fix this, one can simply highlight both the drop command and the create command and then click "Run Statement", resolving the issue.

How do I create a postrgresql database using SQL's DDL on pgadmin4?

I'm learning DDL to create and define an SQL database with Postgresql 10.
I have the something like the following SQL code in an .sql file, and I want to input it in psql or PgAdmin 4, just to test the syntax and see the database structure:
CREATE DATABASE database;
CREATE TYPE t_name AS
( first VARCHAR(30),
last VARCHAR(60)
);
CREATE TABLE telephone_m
( tnumber VARCHAR(15) NOT NULL UNIQUE
);
CREATE TABLE people
( curp CHAR(18) NOT NULL PRIMARY KEY,
pname t_name NOT NULL,
birth_date DATE NOT NULL,
telephone_m VARCHAR(15) REFERENCES telephone_m
);
CREATE TABLE clients
( curp CHAR(18) NOT NULL PRIMARY KEY,
cid SERIAL NOT NULL REFERENCES cards,
clocation VARCHAR(29)
) INHERITS (people);
CREATE TABLE cards
( cid BIGSERIAL NOT NULL PRIMARY KEY,
curp CHAR(18) NOT NULL REFERENCES clients,
trips SMALLINT,
distance NUMERIC,
points NUMERIC
);
CREATE TABLE drivers
( curp CHAR(18) NOT NULL PRIMARY KEY,
rfc CHAR(22) NOT NULL UNIQUE,
adress t_adress NOT NULL
) INHERITS (people);
I've tried in PgAdmin 4 making right-click on a new database -> CREATE Script, it opens Query Editor, I copy paste my code and execute it, but it returns:
ERROR: CREATE DATABASE cannot be executed from a function or multi-command string
SQL state: 25001
I've also tried using Query Tool directly from the PgAdmin tools menu with the same results.
The database is created just fine. But if you want to create object in the new DB, you have to connect to it. In any client, including pgAdmin4.
And you cannot run CREATE DATABASE inside of a transaction. Must be committed on it's own. Executing multiple commands at once is automatically wrapped into a single transaction in pgAdmin.
You have to execute CREATE DATABASE mydb; on its own (for instance by selecting only that line and pressing F5 while being connected to any DB, even the maintenance db "postgres". Then click on "Databases" in the object browser in the pgadmin4 main window / tab, hit F5 to refresh the view, click on the new DB, open up a new query tool with the flash icon (in a new window / tab) and execute the rest of your script there.
psql scripts manage by using the meta-command \c to connect to the new db after creating it, within the same session.
Asides:
"database" is no good name for a database.
CREATE TYPE AS (...), but just CREATE TABLE (...). No AS.
And you typically don't want to use the data type CHAR(18). See:
Any downsides of using data type "text" for storing strings?
Get sum of integers for UNIQUE ids
What is the overhead for varchar(n)?
Should I add an arbitrary length limit to VARCHAR columns?
There is the ; missing after the CREATE DATABASE database (and perhaps give the db a better name).

How to create a table in PHPMyAdmin?

How do I (or rather, what do I write) a SQL CREATE TABLE command to create a table for Term as defined in the picture to create a table?
I am completely new to mhphpadmin (sql) and am learning this from scratch.
The general syntax is
Create Table Table_name (Column_name1 DataType, Column_name2 DataType,...)
You can create table as
CREATE TABLE Term (Term_Name VARCHAR(25), Term_StartDate DATE, TermEndDate DATE);

Newly added table not working

I am working on DB2 9.7 database. I was using SquirrelSQL for GUI purpose. However ever since I applied an alter command to one of my tables , I started facing problems with the table, and any further select queries asked for "reorg" of the table. to overcome this, I renamed the old table and created new table. However the create query didn't execute properly in Squirrel ,and so downloaded DBViewer for my STS(Spring Source Tool Suite.)I executed the create table query from DBViewer, but the issue now is neither am I able to access the newly created table from my JAVA code , nor from Squirrel.
I am completely clueless as to what could be the problem. Has anyone got any idea?
Following is the Structure of my table:
CREATE TABLE DB2ADMIN.CERT
(
CERT_ID CHAR(36) NOT NULL,
CERT_CD CHAR(1) NOT NULL,
CERT_NBR CHAR(10) NOT NULL,
CERT_REQ_USR_CD_1 CHAR(10),
CERT_REQ_USR_CD_2 CHAR(10),
CERT_REQ_USR_CD_3 CHAR(10),
CERT_REQ_USR_CD_4 CHAR(10),
CERT_REQ_USR_TXT_1 VARCHAR(255),
CERT_REQ_USR_TXT_2 VARCHAR(255),
CERT_REQ_USR_TXT_3 VARCHAR(255),
CERT_REQ_USR_TXT_4 VARCHAR(255),
CERT_REQ_USR_TXT_5 VARCHAR(255),
CERT_REQ_USR_TXT_6 VARCHAR(255),
CERT_REQ_USR_TXT_7 VARCHAR(255),
CERT_REQ_USR_TXT_8 VARCHAR(255),
CERT_REQ_USR_TXT_9 VARCHAR(255),
CERT_REQ_USR_DT DATE,
LAST_MDF_USER_ID CHAR(25) NOT NULL,
LAST_MDF_ACY_TS TIMESTAMP(26,6) NOT NULL,
CONSTRAINT SQL111017085116710 PRIMARY KEY (CERT_ID)
);
In my alter query I changed the datatype of CERT_NBR form INTEGER to CHAR
using the command;
ALTER TABLE CERT ALTER COLUMN CERT_NBR SET DATA TYPE INTEGER
any further select queries asked for "reorg" of the table.
This is a common occurrence after altering tables in DB2. It should be trivially solved by calling:
reorg table table-name;
This is a command-line command, rather than an sql statement, but you can call it via SQL with the admin_cmd procedure:
call sysproc.admin_cmd('reorg table table-name');
I'm not sure why you are unable to access the new table. The error message should help you resolve this. Some possibilities:
You created it with a different username than the one you are trying to access it with.
You never committed after the create table statement.
Something went wrong and the table ended up in an inoperable state.

Autogenerate ID in stored procedure -SQL

I have this stored procedure in SQL Server which I use in visual net to generate values for some table.
CREATE PROCEDURE grabardatos
#codigocliente int,
#nombre varchar(50),
#apellido varchar(50),
#sexo char(1),
#direcion varchar(50),
#telefono varchar(50),
#tipo varchar(50)
AS
BEGIN
INSERT INTO CLIENTES(Numero,Nombre,Apellido,Sexo,Direcion,Telefono,Tipo)
VALUES ( #codigocliente,#nombre,#apellido,#sexo,#direcion,#telefono,#tipo)
END
The parameter #codigocliente is the id of the table which, according to this code, has to be entered manually in visual net. How Can the id be autogenerated in the sql code of the stored procecure instead of being entered manually in visual net?
If the clientes table has an identity key, it will be automatically generated by SQL as part of the INSERT. You can then use ##identity to retrieve it's value.
The add the key to the table, you need to create a column
ALTER TABLE Add IdKey INT IDENTITY(1,1)
Note that during the INSERT, you cannot provide a value for this column...