Access SQL - ALTER COLUMN to AutoNumber? - sql

How can you alter a table in MS Access using SQL to change a data type to AutoNumber?
I have tried to following with no success
ALTER TABLE PERSON ALTER COLUMN PERSON_ID Integer PRIMARY KEY counter
);
ALTER TABLE PERSON ALTER COLUMN PERSON_ID Integer PRIMARY KEY AUTONUMBER
);
ALTER TABLE PERSON ALTER COLUMN PERSON_ID Integer PRIMARY KEY AUTOINCREMENT
);
Each time I get the same issue "Syntax error" and it highlights the last word in the SQL.

For a Data Definition (DDL) query in Access you use COUNTER to define an AutoNumber field. You were trying to use both Integer and counter on the same field, and that won't work.
I just tried this and it worked for me in Access 2010:
ALTER TABLE PERSON ALTER COLUMN PERSON_ID COUNTER PRIMARY KEY
Note that in order for this statement to work
the table must be empty, and
the table must not already have a Primary Key, not even on the [PERSON_ID] field.
If the table already has rows in it then Access will not allow you to convert a Numeric (Long Integer) field to AutoNumber. In that case you need to create a new table with the AutoNumber Primary Key and then insert the rows from the old table into the new table.
For example, for an existing table named [PERSON] with columns
PERSON_ID INTEGER
PERSON_NAME TEXT(50)
you need to create a new table
CREATE TABLE PERSON_NEW (PERSON_ID COUNTER PRIMARY KEY, PERSON_NAME TEXT(50))
and then copy the records over
INSERT INTO PERSON_NEW
SELECT * FROM PERSON

Related

How do you ensure values from a logging table match objects in other tables ?

I have three tables. Two basic tables listing objects and a third table logging changes in database. Here is an example.
create table individual (ind_id integer, age integer, name varchar);
create table organisation (org_id integer, city varchar, name varchar);
create TABLE log_table (log_id integer, object_id integer, table_name varchar, information json, log_date date);
I want to ensure that any row in the log_table corresponds to an existing object in either the individual table or the organisation table. This means that the insertion
insert into log_table (object_id,table_name,information,log_date) values (13,'organisation','{"some":"interesting","information":"on the changes"}','2017-11-09');
is valid only if the table organisation contains a record with the ID 13.
How can I do that in PostgreSQL ? If this is not possible, then I suppose I will have to create one column for the individual table and one for the organisation table in the log_table.
You need an entity table:
create table entity (
entity_id serial primary key,
entity_type text check (entity_type in ('individual','organization'))
)
create table individual (
ind_id integer primary key references entity (entity_id),
age integer, name varchar
);
create table organisation (
org_id integer primary key references entity (entity_id),
city varchar, name varchar
);
create TABLE log_table (
log_id integer primary key,
entity_id integer references entity (entity_id),
information json, log_date date
);
You could also use triggers to solve this problem . Seperate triggers can be made on individual and organisation table which could be on before update ,after update , after insert actions .
You could add one column in log table which would correspond to action performed in base table i.e update or insert .
Also you could add unique constraint on table name and object id .
This would eventually lead to logging every possible operation in table without changing in application code .
Hope this helps !
Starting from your current design you can enforce what you want declaratively by adding to each entity table a constant checked or computed/virtual table/type variant/tag column and a FK (foreign key) (id, table) to the log table.
You have two kinds/types of logged entities. Google sql/database subtypes/polymorphism/inheritance. Or (anti-pattern) 2/many/multiple FKs to 2/many/multiple tables.

Is it possible to create a table and add indexes in the same script

When creating a table using the access user interface you are able to create a table that has indexed fields that allow duplicates but when you are creating SQL scripts to create the table you use the "Unique" key word to add indexes but that doesn't allow duplicates on the field.
Below is the script to create the table with indexes.
CREATE TABLE ASSIGNMENT
(
ASSIGNMENT_ID INTEGER PRIMARY KEY,
TASK_ID INTEGER UNIQUE,
EMPLOYEE_ID INTEGER UNIQUE,
ASSIGNMENT_START_DATE DATETIME,
ASSIGNMENT_END_DATE DATETIME,
SKILL_ID INTEGER UNIQUE
);
This is the result showing EMPLOYEE_ID
And here is how I want the EMPLOYEE_ID to show
I have tried to just use the word Index but the script wont run and has issues saying "Syntax Error"
I'm pretty sure that what you describe cannot be done in a single CREATE TABLE statement. The DDL for Access SQL allows us to specify PRIMARY KEY and UNIQUE Constraints as properties of columns we include in our CREATE TABLE statements, but it does not seem to offer the same convenience if we simply want that column to be Indexed (allowing duplicates).
So, you'll probably just have to do it in two steps:
CREATE TABLE ASSIGNMENT
(
ASSIGNMENT_ID INTEGER PRIMARY KEY,
TASK_ID INTEGER UNIQUE,
EMPLOYEE_ID INTEGER,
ASSIGNMENT_START_DATE DATETIME,
ASSIGNMENT_END_DATE DATETIME,
SKILL_ID INTEGER UNIQUE
)
... followed immediately by ...
CREATE INDEX idxEMPLOYEE_ID ON ASSIGNMENT (EMPLOYEE_ID)

Two or more table with serial with uniq nums in every table

I've 2 table with serial field (in table "m" it's field "uniq" and in table "u" it's field "uniq").
But, if I insert data in (for example) u. Autoincrement function make +1 for next row in u (from 1 to 2), but if after this action I insert data in another table (for example) m autoincrement field write down not next value in column (1,2,3..), but 3, even if in field was 1.
It means, what autoincrement function incremented every single value in database in series, but not in the table.
sorry for such a poor description of the problem and bad english = )
Try something like this if you want having an id which is unique in all tables:
CREATE SEQUENCE id_seq;
CREATE TABLE table1(id INTEGER PRIMARY KEY DEFAULT NEXTVAL('id_seq'),Test1 varchar);
CREATE TABLE table2(id INTEGER PRIMARY KEY DEFAULT NEXTVAL('id_seq'),Test2 varchar);
try something like this to create unique id for each table
CREATE TABLE table3(id serial,Test3 varchar);
CREATE TABLE table4(id serial,Test4 varchar);
SQL Fiddle
If I understand correctly, you want a unique ID over tables "a" and "b". So create one table with a serial column just for having your key (eg. "id_table") and all other tables have this key as foreign key. Every time you need a new ID, you insert in your "id_table" and point to this new key.

Adding column with primary key in existing table

I am trying to add primary key to newly added column in existing table name Product_Details.
New Column added: Product_Detail_ID (int and not null)
I am trying add primary key to Product_Detail_ID (please note: there are no other primary or foreign key assigned to this table)
I am trying with this query but getting error.
ALTER TABLE Product_Details
ADD CONSTRAINT pk_Product_Detils_Product_Detail_ID PRIMARY KEY(Product_Detail_ID)
GO
Error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.Product\_Details' and the index name 'pk\_Product\_Detils'. The duplicate key value is (0).
Am I missing something here? I am using SQL Server 2008 R2. I would appreciate any help.
If you want SQL Server to automatically provide values for the new column, make it an identity.
ALTER TABLE Product_Details DROP COLUMN Product_Detail_ID
GO
ALTER TABLE Product_Details ADD Product_Detail_ID int identity(1,1) not null
GO
ALTER TABLE Product_Details
add CONSTRAINT pk_Product_Detils_Product_Detail_ID primary key(Product_Detail_ID)
GO
In mysql, I was able to achieve with following query
ALTER TABLE table_name ADD new_column int NOT NULL AUTO_INCREMENT primary key
Add Primary Key to First Position
ALTER TABLE table_name
ADD column_name INT PRIMARY KEY AUTO_INCREMENT FIRST;
Reference: Stack Overflow | Tech On The Net
You are getting the error because you have existing data that does not fullfill the constraint.
There are 2 ways to fix it:
clean up the existing data before adding the constraint
add the constraint with the "WITH NOCHECK" option, this will stop sql server checking existing data, only new data will be checked
ALTER TABLE Jaya
ADD CONSTRAINT no primary key(No);
here Jaya is table name,
no is column name,
ADD CONSTRAINT is we giving the primary key keyword
If you want to add a new column say deptId to the existing table say department then you can do it using the below code.
ALTER TABLE department ADD COLUMN deptID INT;
it will create your new column named deptID.
now if you want to add constraint also along with new column while creating it then you can do it using the below code. In the below code I am adding primary key as a constraint. you can add another constraint also instead of primary key like foreign key, default etc.
ALTER TABLE department ADD COLUMN deptID INT NOT NULL ADD CONSTRAINT PRIMARY KEY(deptID);
k. friend
command:
sql> alter table tablename add primary key(col_name);
ex: alter table pk_Product_Detils add primary key(Product_Detail_ID);

Altering SQLite column type and adding PK constraint

How to change the type of a column in a SQLite table?
I've got:
CREATE TABLE table(
id INTEGER,
salt TEXT NOT NULL UNIQUE,
step INT,
insert_date TIMESTAMP
);
I'd like to change salt's type to just TEXT and id's type to INTEGER PRIMARY KEY.
Below is an excerpt from the SQLite manual discussing the ALTER TABLE command (see URL: SQLite Alter Table):
SQLite supports a limited subset of
ALTER TABLE. The ALTER TABLE command
in SQLite allows the user to rename a
table or to add a new column to an
existing table. It is not possible to
rename a colum, remove a column, or
add or remove constraints from a
table.
As the manual states, it is not possible to modify a column's type or constraints, such as converting NULL to NOT NULL. However, there is a work around by
copying the old table to a temporary table,
creating a new table defined as desired, and
copying the data from the temporary table to the new table.
To give credit where credit is due, I learned this from the discussion on Issue #1 of hakanw's django-email-usernames project on bitbucket.org.
CREATE TABLE test_table(
id INTEGER,
salt TEXT NOT NULL UNIQUE,
step INT,
insert_date TIMESTAMP
);
ALTER TABLE test_table RENAME TO test_table_temp;
CREATE TABLE test_table(
id INTEGER PRIMARY KEY,
salt TEXT,
step INT,
insert_date TIMESTAMP
);
INSERT INTO test_table SELECT * FROM test_table_temp;
DROP TABLE test_table_temp;
Notes
I used the table name test_table since SQLite will generate an error if you try to name a table as table.
The INSERT INTO command will fail if your data does not conform to the new table constraints. For instance, if the original test_table contains two id fields with the same integer, you will receive an "SQL error: PRIMARY KEY must be unique" when you execute the "INSERT INTO test_table SELECT * FROM test_table_temp;" command.
For all testing, I used SQLite version 3.4.0 as included as part of Python 2.6.2 running on my 13" Unibody MacBook with Mac OS X 10.5.7.
Since RDBMS is not specified, these are DB2 queries:
Make ID as primary key:
ALTER TABLE table
ADD CONSTRAINT pk_id
PRIMARY KEY (id)
Make salt as not UNIQUE:
ALTER TABLE table
DROP UNIQUE <salt-unique-constraint-name>
Make salt nullable:
ALTER TABLE table
ALTER COLUMN salt DROP NOT NULL
You will need to do a reorg after drop not null. This is to be done from the command prompt.
reorg table <tableName>
In this case you can make salt to nullable and remove unique constraint. Also If id column does not contain any null or duplicate values you can safely make it primary key using sql server management studio. below is the screen shot. hope it makes it clearer:
alt text http://img265.imageshack.us/img265/7418/91573473.png
or use following sql:
alter table <TableName> modify salt text null
alter table <TableName> drop constraint <Unique Constraint Name>
alter table <TableName> modify id int not null
alter table <TableName> add constraint pk<Table>d primary key (id)