I'm attempting to make a table for the first time using postgres and the examples I'm seeing are kind of throwing me off. When it comes to creating a schema, I have a schema.sql file that contains my schema as follows:
CREATE TABLE IF NOT EXISTS orders
(
order_id INTEGER NOT NULL,
order_amount INTEGER NOT NULL
);
COMMENT ON COLUMN orders.order_id IS 'The order ID';
COMMENT ON COLUMN orders.order_amount IS 'The order amount';
Now I'd upload that schema by doing the following:
psql -d mydb -f /usr/share/schema.sql
Now when it comes time to create the table I'm suppose to do something like this:
create table schema.orders(
order_id INT NOT NULL,
order_amount INT NOT NULL
);
The uploading of the schema.sql file is what confuses me. What is all the information inside the file used for. I thought by uploading the schema i'm providing the model to create the table, but running create table schema.orders seems to be doing just that.
What you call "upload" is actually executing a script file (with SQL DDL commands in it).
I thought by uploading the schema i'm providing the model to create the table
You are creating the table by executing that script. The second CREATE TABLE command is almost but not quite doing the same. Crucial difference (besides the missing comments): A schema-qualified table name. And your schema happens to be named "schema", which is a pretty bad idea, but allowed.
Now, the term "schema" is used for two different things:
The general database structure created with SQL DDL commands.
A SCHEMA which is similar to a directory in a file system.
The term just happens to be the same for either, but one has nothing to do with the other.
Depending on the schema search path, the first invocation of CREATE TABLE may or may not have created another table in a different schema. You need to understand the role of the search path in Postgres:
How does the search_path influence identifier resolution and the "current schema"
Related
I have a requirement of saving employees image in database. I have been asked to use File Tables. After googling on this I got some fine contents as to how to get started with File Tables. And I managed to create them, also inserting data to these tables is as simple as copy/paste to specified folder and the data gets inserted into the table. The problem is how do I relate each employee row set with their respective images
The overall flow will be like the employee will upload his/her image or doc through front end, which will save the image on the server. the problem is how to add reference of employee with its respective image. One option can be having a FileName column in the employee table which refers to the name column in the FileTable, but I need something more efficient such as relating the id's. Any other way of achieving this would be appreciated.
First of it consumed a lot of time to get things right as filetable being a new feature introduced from SQLSERVER 2012 onwards. Secondly this is the approach I took to counter my issue. I will be providing some usefull links to make life easier for other developers. Hope it helps.
File table is almost similar to normal SQL tables, but has some configurations to be made to get it started, as it resides in a separate section of your database, inside tables-->FIleTables. Since the table structure is predefined, you cannot change the table schema. So the approach I took is to refer the stream_id as the reference key to link with the table that I want to use and handle the constrains logic through stored procedure. In my scenario the Employee table will have a stream_id column which will be linked to the File table via stream_id, also to make rows in the File table unique, I inserted the Employee Id as the name of the stored image and not the actual name of the file. With this even if anyone tries to insert the file directly by copy/paste it wouldn't have any relation with the Employee table, also you can provide access right to give desired permission. Check the links for more details. And that's it, with a little bit of tweaks I was able to solve my issue.
Below SQL scripts will be helpful to activate file stream at instance level at one shot.
EXEC sp_configure filestream_access_level, 2
RECONFIGURE
GO
--For new DB
CREATE DATABASE <DATABASE name>
WITH FILESTREAM
(
NON_TRANSACTED_ACCESS = FULL,
DIRECTORY_NAME = N'<DIRECTORY name>'
);
GO
--If you have an existing DB
ALTER DATABASE <DATABASE name>
ADD FILEGROUP <File group name>
CONTAINS FILESTREAM
GO
ALTER DATABASE <DATABASE name>
ADD FILE (NAME='<File group name>', FILENAME='<DIRECTORY name>')
TO FILEGROUP <File group name>
GO
ALTER DATABASE <DATABASE name>
SET FILESTREAM ( NON_TRANSACTED_ACCESS = FULL, DIRECTORY_NAME = N'<File
group name>')
GO
use <DATABASE name>
GO
CREATE TABLE <Filetable NAME> AS FileTable;
GO
Also some links which are very helpful:
https://www.mssqltips.com/sqlservertip/2667/filetable-feature-in-sql-server-2012/
http://sql-articles.com/articles/general/working-with-filetables/
https://michaelfirsov.wordpress.com/working-with-sql-server-file-tables-part-1/
https://michaelfirsov.wordpress.com/working-with-sql-server-file-tables-part-2/
https://msdn.microsoft.com/pl-pl/library/gg492084(v=sql.110).aspx
Thanks.
Wouldn't just having a "joining (many-to-many) table" in between employer and the filetable be just as easy? You wouldn't have to use it as a many-to-many table. Call it EmployeeImages and add a description attribute/property i.e "Hiring photo", "Just got fired photo". with both primary keys from employee and filetable. simples!
You have to insert in your program the code for copying file.
File.Copy(...) Instead of just copying and pasting into file system.
So that, each instance that your File.Copy executes, you can get its respective stream_id, which then you attach on your employees table..
In SQL Server Database Engine I have a table named Table A.
I deleted the table using graphical interface, but when I wanted to create a table with same name, the error shows
The object already exists
What is the remedy of this situation?
The following steps should help you track down what is going on and help you create your table:
Right-click on your database and select refresh
Verify that your table does not exist under this database.
If you table is
not shown here, then very likely your table is displayed under the
master database.
To create a table in your selected database,
first select the database and then run your query.
A better
option for number 4, just to be sure you are specifying the correct
database is to run the command use dbname; (where dbname is
the name of your database). Do this on the line above your create table code.
In HSLQDB v 2.3.1 there is a create type clause for defining UDTs. But there appears to be no alter type clause, as far as the docs are concerned (and the db returns a unexpected token error if I try this).
Is it possible to amend/drop a UDT in HSQLDB? What would be the best practice, if for example I originally created
create type CURRENCY_ID as char(3)
because I decide I'm going to use ISO codes. But then I actually decide that I'm going to store the codes as integers instead. What is the best way to modify the schema in my db? (this is a synthetic example, obviously I wouldn't use integers in this case).
I guess I might do
alter table inventory alter column ccy set data type int
drop type CURRENCY_ID
create type CURRENCY_ID as int
alter table inventory alter column ccy set data type CURRENCY_ID
but is there a better way to do this?
After trying various methods, I ended up writing a script to edit the *.script file of the database directly. It's a plain text file with SQL commands that recreates the DB programmatically. In detail:
open db, shutdown compact
Edit the script file: replace the type definition, e.g. create type XXX as int to create type XXX as char(4)
For each table, replace the insert into table XXX values (i,...) with insert into table XXX values('str',...). This was done with a script that had the mappings from the old (int) value into the new (char) value.
In my particular case, I was changing a primary key, so I had to remove the identity directive from the create table statement, and also I had to remove a line that had a alter table XXX alter column YYY restart sequence 123.
save and close script file, open db, shutdown compact
This isn't great, but it worked. Advantages :
Ability to re-define UDT.
Ability to map the table values programmatically.
Method is generic and can be used for other schema changes, beside UDTs.
Cons
No checking that schema is consistent (although it does throw up errors if it can't read the script).
Dangerous when reading file as a text file. e.g. what if I have a VARCHAR column with newlines in it? When I parse the script file and write it back, this would need to be escaped.
Not sure if this works with non-memory DBs. i.e. those that don't only have a *.script file when shutdown.
Probably not efficient for large DBs. My DB was small ~ 1MB.
When I create table that has definition of FK's directly in CREATE command and target table does not exists yet, results in error.
Can checking, if target table exists, be somehow suspended?
my DBMS is Postgres.
Example (pseudocode):
create table "Bar"
foo_id integer FK of "Foo"."id",
someattr text;
create table "Foo"
id integer;
Example is in wrong order, thats why it wont run.
I'm trying to recreate databse in batch, based on definitions in many sql files.
When I create table that has definition of FK's directly in CREATE command and target table does not exists yet, results in error.
Can checking, if target table exists, be somehow suspended?
The best ways to deal with this are likely:
Create your tables in the correct order, or
Create the constraints
outside the table creation, after all tables are created.
Brute force is always an option.
Keep on running your DDL scripts in until you get a run with no errors.
More elegance requires a sequential structuring of your scripts.
Adding existence checks is possible, but I am not too familiar with the postgres metadata.
This is probably stupid simple, but for some reason I'm having trouble getting it to work. I have a typical import script I'm trying to run on a MS SQL server with one master user (as opposed to a single user with only access to one database).
When I run the .SQL script, it creates the database and then starts to create tables. Here's where it gets interesting. It's not creating the databases under the DB I just made. It's throwing the tables under the "System Databases" view and not restricting the table creation to the DB that was just created.
I have tried:
CREATE TABLE table_name
CREATE TABLE database_name.table_name
Maybe I'm overlooking something really easy. I don't usually run into this with MySQL with a single user mapped to one database, I think since the user can only see that one database, so MySQL assumes it must be the one to work with.
The difference now is that I'm using MSSQL 2008 and maybe it works a little differently and I'm overlooking something. Thanks for your help!
Tried this too. No luck. Says database doesn't exist when it tries to create the table. I would think being a top/down read of the query script it would first create the database, then try to create the table afterwards.
CREATE DATABASE DATABASENAME;
CREATE TABLE DATABASENAME.dbo.TABLENAME
(
field_one VARCHAR(100) NOT NULL,
field_two INT NOT NULL,
PRIMARY KEY(field_one)
)
This is a working example after getting it all figured out. This syntax works well and I don't need to specify the DBO pathing stuff before table names this way. Cleaner and got me the results I was looking for. Thanks everyone.
IF Db_id('DBNAME') IS NULL
CREATE DATABASE DBNAME;
GO
USE [DBNAME];
GO
CREATE TABLE TABLENAME
(
COL1 VARCHAR(100) NOT NULL,
COL2 INT NOT NULL,
PRIMARY KEY(COL2)
)
INSERT INTO TABLENAME
(COL1,
COL2)
VALUES('1234',1001),
('1234',1002),
('1234',1003),
('1234',1004)
It basically just does a check to make sure database is created before doing anything else, then sets the USE database to the one I'm working with. Everything else is just normal SQL, so have fun. Cheers!
Probably you need to include the USE sentence at the begining of your script in order to indicate the database as follows:
USE [database_name]
GO
By default SQL-SERVER use the master DB that´s listed under system databases.
Other way is to use the database prefix, but including the owner:
INSERT INTO database_name.dbo.table_name
INSERT INTO database_name..table_name