creating multiple tables with single sql command - sql

I searched for this here and on google and surprisingly couldn't find an answer. I tried to create syntax to submit to mysql that would create multiple tables with the same columns, but it returned an error. Can you point out what is wrong with my syntax, or if this is even possible?
CREATE TABLE news, life
(
id int PRIMARY KEY AUTO_INCREMENT ,
name varchar( 30 ) ,
email varchar( 50 ) ,
COMMENT text,
datetime datetime,
ip varchar( 20 )
)

you are in mysql so you can use the LIKE clause of the CREATE TABLE command; that way you will also get column attributes and indexes copied over e.g.
CREATE TABLE new_tbl LIKE orig_tbl;
see http://dev.mysql.com/doc/refman/5.1/en/create-table.html
Use LIKE to create an empty table
based on the definition of another
table, including any column attributes
and indexes defined in the original
table: CREATE TABLE new_tbl LIKE
orig_tbl; The copy is created using
the same version of the table storage
format as the original table. The
SELECT privilege is required on the
original table. LIKE works only for
base tables, not for views. CREATE
TABLE ... LIKE does not preserve any
DATA DIRECTORY or INDEX DIRECTORY
table options that were specified for
the original table, or any foreign key
definitions.

It's not possible like that.
Think about your table design. This sounds like you should consider creating a single table and adding another column type that will be news or life (or a reference to another table defining types).
If you really need two tables, create your first table:
CREATE TABLE news
(
id int PRIMARY KEY AUTO_INCREMENT ,
name varchar( 30 ) ,
email varchar( 50 ) ,
COMMENT text,
datetime datetime,
ip varchar( 20 )
)
and then
CREATE TABLE life AS ( SELECT * FROM news where 1=2 );
Indexes and constraints (UNIQUE, PRIMARY KEY, FOREIGN KEY) will not be copied though. You will have to handle them yourself.

Related

Create indeterminant CHECK CONSTRAINT that works in SQL Server Partitioned View

Context
A SQL partitioned view reads tables like any other view. However, what makes them special is that they allow me to write to the underlying tables through when a portioning key column is indicated by using a CHECK CONSTRAINT on the underlying tables.
Read more in the Online Docs.
An Example
For example, here a CHECK CONSTRAINT validates the [Year] column value is always 2022. The value of 2022 in the CHECK is a hard coded (deterministic) value. During a SELECT operation, the view ignores the CHECK but during an INSERT operation, the CHECK instructs the view to which table it should insert the record(s).
CREATE TABLE Part2022
(
Id UNIQUEIDENTIFIER UNIQUE CLUSTERED
, Year INT CONSTRAINT req2022 CHECK (Year = 2022)
PRIMARY KEY NONCLUSTERED (Id, Year)
);
Using this approach, a partitioning view would look like this:
CREATE VIEW Parts AS
SELECT * FROM Part2022
UNION ALL SELECT * FROM Part2021
UNION ALL SELECT * FROM Part2020
This works just fine.
The question
I understand the issue, but I wonder if some clever data engineer out there has figured a workaround that would enable a different approach - something similar to this:
CREATE TABLE PartCurrent
(
Id UNIQUEIDENTIFIER UNIQUE CLUSTERED
, Year INT CONSTRAINT reqCurrent CHECK (Year = YEAR(GETUTCDATE()))
PRIMARY KEY NONCLUSTERED (Id, Year)
);
Of course, this does not work. Though the CHECK CONSTRAINT can be applied to the table without issue, including this table in a partitioned view now results in:
Msg 4436, Level 16, State 12, Line 53 view is not updatable because a partitioning column was not found.
Q: Is there a way to use an indeterminate CHECK CONSTRAINT with a partitioned view?
PS: I know what partitioned tables are and when to use them in a model. In this case, though, they do not meet the requirements. As a result, I am asking about partitioned views. Thx.
Answer: Though a check constraint condition can be dynamic in a table, if that table is in a partition view, checks on partition key columns must be hardcoded. This is by design.
Read the Docs.
That is to say, you must do something like this:
CREATE TABLE Part2022
(
Id UNIQUEIDENTIFIER UNIQUE CLUSTERED
, Year INT CONSTRAINT req2022 CHECK (Year = 2022)
PRIMARY KEY NONCLUSTERED (Id, Year)
);
You cannot do something like this:
CREATE TABLE Part2022
(
Id UNIQUEIDENTIFIER UNIQUE CLUSTERED
, Year INT CONSTRAINT req2022 CHECK (Year = YEAR(GETUTCDATE()))
PRIMARY KEY NONCLUSTERED (Id, Year)
);

Automatic uniqueidentifier during table design

I've created a new table and made column id the primary key and defined it as uniqueidentifier.
Is there a way during the tables design in SQL Server Management Studio to assign a rule that all new rows auto generate a new uniqueidentifier in the id column?
At the moment to make my form (made on Retool) write to the table I need to type out a random set of characters, essentially self creating my own uniqueidentifier which obviously isn't correct.
Avoid the designers, they've been a complete and utter mess for 17 years. Do this in a query window:
USE tempdb;
GO
CREATE TABLE dbo.what
(
id uniqueidentifier NOT NULL
CONSTRAINT DF_what_id DEFAULT(NEWSEQUENTIALID()),
-- or NEWID() if you like page splits
name nvarchar(128),
CONSTRAINT PK_what PRIMARY KEY (id)
);
INSERT dbo.what(name) VALUES(N'hi'),(N'there');
SELECT id, name FROM dbo.what;
Output (yours will have different values for id):
id
name
84c37c76-8c0e-ed11-ba5d-00163ef319ff
hi
85c37c76-8c0e-ed11-ba5d-00163ef319ff
there

Oracle SQL: "GENERATED ALWAYS" with a specified sequence

I have two tables that I would like to let them share the same sequence to populate the primary key ID column. However, I also don't want the user to specify or change the value for the ID column.
By using the code below, I can let two tables share the same sequence.
CREATE TABLE T1
(
ID INTEGER DEFAULT SEQ_1.nextval NOT NULL
);
This code will use its own sequence and prevent users from changing or specifying with INSERT:
CREATE TABLE T1
(
ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL
);
Is there a way that can both world? Something like this:
CREATE TABLE T1
(
ID INTEGER GENERATED ALWAYS AS ( SEQ_1.nextval ) NOT NULL
);
Regarding the use case, as #Sujitmohanty30 asked, the reason that I raised this question:
I'm thinking to implement inheritance in the database, consider this UML diagram (I can't directly post images due to insufficient reputation, and sorry for being lack of imagination).
ANIMAL is abstract and all inheritance is mandatory. This means no instance of ANIMAL should be created. Furthermore, there is an one-to-many relationship between ANIMAL and ZOO_KEEPER.
Therefore, I came up with this idea:
CREATE SEQUENCE ANIMAL_ID_SEQ;
CREATE TABLE HORSE
(
ID INT DEFAULT ANIMAL_ID_SEQ.nextval NOT NULL PRIMARY KEY,
HEIGHT DECIMAL(3, 2) NOT NULL
);
CREATE TABLE DOLPHIN
(
ID INT DEFAULT ANIMAL_ID_SEQ.nextval NOT NULL PRIMARY KEY,
LENGTH DECIMAL(3, 2) NOT NULL
);
CREATE MATERIALIZED VIEW LOG ON HORSE WITH ROWID;
CREATE MATERIALIZED VIEW LOG ON DOLPHIN WITH ROWID;
CREATE MATERIALIZED VIEW ANIMAL
REFRESH FAST ON COMMIT
AS
SELECT 'horse' AS TYPE, ROWID AS RID, ID -- TYPE column is used as a UNION ALL marker
FROM HORSE
UNION ALL
SELECT 'dolphin' AS TYPE, ROWID AS RID, ID
FROM DOLPHIN;
ALTER TABLE ANIMAL
ADD CONSTRAINT ANIMAL_PK PRIMARY KEY (ID);
CREATE TABLE ZOO_KEEPER
(
NAME VARCHAR(50) NOT NULL PRIMARY KEY,
ANIMAL_ID INT NOT NULL REFERENCES ANIMAL (ID)
);
In this case, the use of the shared sequence is to avoid collision in ANIMAL mview. It uses DEFAULT to get the next ID of the shared sequence. However, using DEFAULT doesn't prevent users from manually INSERTing the ID field or UPDATE the value of it.
You can create a master view/table and generate the sequence in it.
Then copy it as column values into both tables while inserting.
Another option could be inserting into both tables at same time.Use SEQ.NEXTVAL to insert into first table to get a new ID, and then SEQ.CURRVAL to copy same id in the table.
No, you cant have anything like this because ID is independently generated for each of the tables and this can be done only using sequence when you are inserting the data in both the tables at the same time.
You should normalize your data schema: add column animal_type into the table and create composite primary key on both columns

Add files to multiple tables M:N

What is The best Data model for Add multiple files to The multiple tables? I have for example 5 tables articles, blogs, posts... and for each item I would like to store multiple files. Files table contains only filepaths (not physicaly files).
Example:
Im using The links table, but when I create in the future The new table for example "comments", then I need to add new column to The links table.
Is there a better way of modeling such data?
One way to solve this is to use the table inheritance pattern. The main idea is to have a base table (let's call it content) with general shared information about all the items (e.g., creation date) and most importantly, the relationship with files. Then, you may add additional content types in the future without having to worry about their relation to files, since the content parent type already handles it.
E.g.:
CREATE TABLE flies (
id NUMERIC PRIMARY KEY,
path VARCHAR(100) NOT NULL
);
CREATE TABLE content (
id NUMERIC PRIMARY KEY,
created TIMESTAMP NOT NULL
);
CREATE TABLE links (
file_id NUMERIC NOT NULL REFERENCES files(id),
content_id NUMERIC NOT NULL REFERENCES content(id),
PRIMARY KEY (file_id, content_id)
);
CREATE TABLE articles (
id NUMERIC PRIMARY KEY REFERENCES content(id),
title VARCHAR(400),
subtitle VARCHAR(400)
);
-- etc...

SQL - Field Grouping and temporary data restructruing

I would like to apologize first about my title, because I understand it may be technically incorrect
I currently have a database with multiple tables, 4 of them are relevant in this example.
FORMS
FIELDS
ENTRIES
VALUES
Below is a shortened version of the tables
Create table Form_Master
(
form_id int identity primary key ,
form_name varchar(255) ,
form_description varchar(255),
form_create_date date ,
)
Create table Field_Master
(field_id int identity primary key,
form_ID int foreign key references Form_Master(form_id),
field_name varchar(255),
type_ID int
)
Create table Entry_Master
(
entry_id int identity primary key,
entry_date date,
form_id int foreign key references Form_Master(form_id),
)
Create table Value_Master
(
value_id int identity primary key,
value varchar(255),
field_id int foreign key references Field_Master(field_id),
entry_id int foreign key references Entry_Master(entry_id),
)
The purpose of these tables is to create a dynamic method of capturing and retrieving information - a form is a table, a field is a column, and entry is a row and a value is a cell
Currently when I am retrieving information from a form, I create a temporary table, with columns as such in the field_master, then select all entries linked to the form, and the values linked to those entries, and insert them into the temporary table I have just created.
The reason for the temporary table is to restructure the data into an organised format and display it in a DataGridView.
My problem is one of performance, creating the table as mentioned above is becoming slower as forms exceed fields > 20 or entries linked to a form exceeds > 100
My questions are:
Is there a way to select the data directly from field_master in the format of the temporary table mentioned above?
Do you think I should re-think my database design?
Is there an easier method to do what I am trying to do?
Any input will be appreciated, I do know how to use Google, however in this instance I am not sure what exactly to look for, so even a keyword would be nice.