Auto-increment primary key in SQL tables - sql-server-2008

Using Sql Express Management Studio 2008 GUI (not with coding), how can I make a primary key auto-incremented?
Let me explain: there is a table which has a column named "id" and the items of this column are set to be primary keys. I want to make this column auto-incremented, but how?
Cheers

Presumably you are in the design of the table. If not: right click the table name - "Design".
Click the required column.
In "Column properties" (at the bottom), scroll to the "Identity Specification" section, expand it, then toggle "(Is Identity)" to "Yes".

Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):
CREATE TABLE "dbo"."TableName"
(
id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
name varchar(20),
);
the insert statement should list all columns except the id column (it will be filled with autoincremented value):
INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');
and the result of
SELECT id, name FROM "dbo"."TableName";
will be
id name
--------------------------
1 alpha
2 beta

Right-click on the table in SSMS, 'Design' it, and click on the id column. In the properties, set the identity to be seeded # e.g. 1 and to have increment of 1 - save and you're done.

for those who are having the issue of it still not letting you save once it is changed according to answer below, do the following:
tools -> options -> designers -> Table and Database Designers -> uncheck "prevent saving changes that require table re-creation" box -> OK
and try to save as it should work now

I don't have Express Management Studio on this machine, so I'm going based on memory. I think you need to set the column as "IDENTITY", and there should be a [+] under properties where you can expand, and set auto-increment to true.

I think there is a way to do it at definition stage like this
create table employee(
id int identity,
name varchar(50),
primary key(id)
)..
I am trying to see if there is a way to alter an existing table and make the column as Identity which does not look possible theoretically (as the existing values might need modification)

Related

Validation rule to compare duplicates across multiple fields in access [duplicate]

We'd like to prevent record duplication in our MS access database using a multicolumn unique index. Because of how the data is sent (via network), duplicate data is sometimes received. The data source does not send a unique ID, so the simplest option is to prevent duplicate records being inserted.
According to Unique Index Design Guidelines:
With multicolumn unique indexes, the
index guarantees that each combination
of values in the index key is unique.
For example, if a unique index is
created on a combination of LastName,
FirstName, and MiddleName columns, no
two rows in the table could have the
same combination of values for these
columns.
This is for SQL 2005 however, so I'm not sure it's possible using MS access.
I guess an alternative is to perhaps use the query (pseudo code):
insert into foobar (a, b, c) values ('x', 'y', 'z')
where (a <> 'x') and (b <> 'y') and (c <> 'z')
... but I feel like an index would be better.
Turns out you can create a multi-column unique index on an MS access database, but it's a little crazy if you want to do this via the GUI. There's also a limitation; you can only use 10 columns per index.
Anyway, here's how you create a multi-column unique index on an MS access database.
Open the table in design mode, and Design, select Indexes.
Create a new row and enter a value in the Index Name cell,
Choose the first column from the drop down menu.
Add a new row and leave the Index Name cell blank.
Choose the second column, and so on.
Here's what it should look like:
Open the table in design view in MS Access, select the three columns that you want to make into the unique index, and then click the little key on the toolbar. You cannot have null values in a primary key (set).
We can make multi data to be unique data without set them as primary key.
(Note: only 1 data in the table can be primary key)
Step to set the data value as unique data (for MS ACCESS 2007 - 2010)
Open selected table in Design View
Click (Highlight) the specific column/attribute that you wish to set as unique
At the bottom of the table you will see "Index Properties" for that specific column
Find "Indexed" column, currently the data in Indexed text box is "No", change the data by click at the end of text box, choose "Yes(No Duplicates)"
Really hopes this methods can helps all of you! :)
I had the problem Nick Bolton reported above. Setting 2 fields (Foo, Bar) as PK set Foo to unique, when I wanted only the combination of Foo + Bar to be unique.
The problem turned out to be that I had created a 1:1 relationship to another table, linking on Foo. I deleted the relationship, set up the 2-field PK the way I wanted, and then reinstated the relationship, and it works as desired.
A trick I found is that in order to get a 2 column primary key (in the parent table) to be a child tableĀ“s 2(FK)+n primary key is to FIRST CHOOSE the indexed attribute as FISRT key attribute and THEN the not indexed attribute as a SECOND key attribute in the "Modify Relations Dialog Box" #Relations Window.
It will serve as Unique key in Ms Access 2007/2010

Can phpMyAdmin "internal relations" be configured to do lookup on one column and insert values from another?

I have a MySQL database with two InnoDB tables that I administer with phpMyAdmin v4.5.2. The table have a foreign key constraint on an "id" column.
When I define an "internal relation" and then goto the "insert" page for the table I now see a new icon next to my column with the internal relation defined. This is nice but when I click the icon I can only lookup ID values...
What would be really nice is if I could do the lookup on the internal relation by a "name" column (i.e. the SYMBOL varchar field), but upon choosing an item, it would populate the ID from that row (the SYMBOL_LIST_ID column) into the insert field. I've been searching but haven't been able to find an example of how to do this -- has anyone setup this type of internal relation functionality? Thanks!
Here's an example of my table structure:
http://sqlfiddle.com/#!9/4e921/1
I'm unable to view your SQL Fiddle, but it sounds like you just want the lookup value to show in the table instead of the key ID.
By the way, since you are using the InnoDB table type, I suggest using the actual MySQL relations instead of phpMyAdmin's internal relations. This will allow your other applications to take advantage of the relations you configure.
There are two ways to configure relations, Relation view (available under the Structure tab of a table), or Designer (on the main list of tabs when viewing a database). It sounds like you're already using Relation View and have correctly defined your foreign keys there, so on the table where you're doing the lookup go to the Relation View and scroll down to "Choose column to display", then pick the column you want to look up.
In my case, I built a table "customer":
id int primary key
name varchar(255)
city_ref int index
and "customer_city":
id int primary key
city varchar(255)
Then I configured my foreign key from the Relation view in "customer":
Finally from the Relation view for "customer_city", picking "city" as the column to display:
Now when I go to insert a row to "customer", I get the lookup value presented in the "city" field:
Note that it appears twice, once sorted by the ID and once sorted by city; that way I can insert quickly if I know the ID and by referenced value if I don't.

Version control independent records and list them all base on a configuration

I have read this two questions:
Is there a MySQL option/feature to track history of changes to records?
How to version control a record in a database
I understood how the version system should work but I have a a particular question for my situation.
For example I have this table:
Let us say that this table has around 4000 records in it. I will display to the user 100 records once based on a preset configuration, for example display all record where record A value is foo.
The user now has the possibility to change any of the 100 records, for example let us say that he changes 4 records and he leaves the other 96 records untouched.
My question is:
If the user changes only 4 record from the preset configuration what is the best way to keep track of the changes and beside that the track of configurations (the way that the 100 record looked like in a particular date before changing).
I can add a start_date and end_date fields to keep track of the configurations in another table but it doesn't feel right to have a table and fill it with 100 record from which only 4 record changed just to be able to know how the configuration looked at a certain date and what record changed according to the version from that date. At the end I will end up with hundreds of duplicated content that has only the date field different. What is the ideal solution for this situation?
Later Edit:
The main idea is to obtain something like this:
I want to be able to see each configuration version (version 1, 2, 3, 4) from the specific creation date. Each configuration is containing old rows (from previous configuration version) + the rows modified by the user in the new version.
Based on our chat discussion, and this link as a talking point,
consider the following schema and expand upon it.
-- drop table bom
create table bom
( -- Bill of Materials
bomId int auto_increment primary key
-- other high level fields
);
-- drop table bomVersion
create table bomVersion
( -- Bill of Materials / version
id int auto_increment primary key,
bomId int not null,
-- other high level fields
version int not null, -- you need to figure out how to increment this, and it is not an auto inc here
description varchar(1000), -- ie: let's add a Floppy Drive
creationDate datetime not null,
unique key(bomId,version), -- no dupes
-- yes, (bomId,version) could be the PK but I chose not to
CONSTRAINT fk_version_bom FOREIGN KEY (bomId) REFERENCES bom(bomId)
);
-- drop table bvDetails;
create table bvDetails
( -- Bill of Materials / Version / Details
id int auto_increment primary key,
bvId int not null,
lineNumber int not null, -- if ordering is important
partId int not null,
qty int not null, -- I am no BOM expert, is this stuff in there?
price decimal(12,2) not null, -- I am no BOM expert, is this stuff in there?
-- FK constraints back to Part table and bvId, below shows one of them
CONSTRAINT fk_det_bomversion FOREIGN KEY (bvId) REFERENCES bomVersion(id)
);
One of the biggest challenges is how to capture the changes made in Part descriptions if they change. So in that link at the very top, if that Case SX1040 has a change in description from Easy Access to Easy Access / Well vented.
So in that case a re-print of a BOM (that was supposed to be nailed down by ISO standards) is going to change. That is not good. So you need to have an audit, a history, of changes to rows that are textual, and save those ids (like for the Part Number). So to be clear, though you can have a Parts table, also have a PartsHistory table (and the id's from the latter go in the bom).
The numerics like price and qty are cool to save like in the above schema. It is the textual history changes that is problematic, and you need to solve that as described in the previous paragraph.
Note, I once wrote a system where in the case of changes to the text columns, we would keep all the revisions all in the same table and have only 1 row (say, for that part) marked as active='Y' for any given item. This way a join was not necessary to the other history table. Either way, you have flexibility from your GUI to select which version you want. Remember from an audit standpoint, you need to have an updateBy (personId) and an updatedDt in these tables.
Edit
Your question just changed. See new column in table bomVersion

Unique on Compound Columns

I am trying to ensure that the values in RESTAURANTID and TABLENUMBER, together, are Unique using PowerDesigner (12.5). I've tried creating an alternate key which resulted in the following in my .sql file:
create table TABLES
(
TABLEID int not null,
RESTAURANTID int not null,
TABLENUMBER int not null,
primary key (TABLESID),
key AK_mykey (RESTAURANTID, TABLENUMBER)
);
However with this, I can still enter identical values for RESTAURANTID and TABLENUMBER more than once.
I used this http://www.tek-tips.com/viewthread.cfm?qid=403554 to create the alternate key in PowerDesigner.
Would anyone know the proper way to achieve this in PowerDesigner?
Note: This isn't a duplicate of the question posted above as I'm looking for a way to achieve this in PowerDesigner without having to edit the generated sql file afterwards.
The unique property for keys (other than primary) in MySQL is stored as an extended attribute on the key.
You can modify it by displaying, and going to the MySQL tab in the Key properties dialog.
Or, in Model>Keys, you can use the Customize Columns and Filter button to show the Ext Unique (extended) property in the list of keys, so that you can set this unique property on several keys at once.
Or, you can create your own copy of the MySQL DBMS, and edit it. Under Profile>Key (using the right-click), add an event handler Initialize with the following Event Handler Script, so that each new key has ExtUnique set:
Function %Initialize%(obj)
obj.setextendedattribute "ExtUnique",true
%Initialize% = True
End Function
You are just adding a normal index. What you need is a unique index. Just replace key AK_mykey (RESTAURANTID, TABLENUMBER) with unique key AK_mykey (RESTAURANTID, TABLENUMBER) in your query and you are done.
In Power Designer:
Open the "TABLES" table properties (right click -> properties)
Keys tab
Insert row (name it to "AK_mykey")
Apply (previously inserted row saved)
On the "AK_mykey" row: right click -> properties
Columns tab
Add columns button
Select the required columns (RESTAURANTID, TABLENUMBER)
OK, OK, OK buttons
+1 You can check the result in table properties preview tab.
alter table TABLES
add unique AK_mykey (RESTAURANTID, TABLENUMBER);

How to add auto-increment to column in mysql database using phpmyadmin?

I've been trying to add auto-increment to one of my columns (basically an ID) but I can't find the auto-increment option for my column. Any idea where it is?
To use the GUI:
Click the STRUCTURE tab to see the list of existing fields
To set a field as the PRIMARY FIELD, click the gold key -- it will turn silver.
To set a field (usually the same field) as auto-increment:
a. Click CHANGE for that field
b. Look to the far right and checkmark the AI box
c. Click SAVE button
You can add it like this
ALTER TABLE your_table
MODIFY some_column INT NOT NULL AUTO_INCREMENT;
A couple quick points based on recent experience:
To the original question, how to select auto-increment with phpmyadmin, it's the small AI check box on the change screen for a field name.
When I tried the "ALTER TABLE tablew_name CHANGE id id BIGINT(20) NOT NULL AUTO_INCREMENT;" solution above, phpmyadmin gave me an error message saying the field had to have a key. I selected a Unique key and the error message went away and the field now auto increments.
This wont work if there are any foreign keys defined, and that is very likely for id fields.
use:
ALTER TABLE tablew_name CHANGE id id BIGINT(20) NOT NULL AUTO_INCREMENT;
instead
The SQL script is correct
ALTER TABLE your_table MODIFY some_column INT NOT NULL AUTO_INCREMENT;
but if you try so make before in the visual mode, with the mysql version 4.7.4, in the struct of the table
Appear when you create the table one option to say "A_I" , if you put your mouse appear message with AUTO_INCREMENT (The version of the foto is in Spanish version)
If you are using xampp:
step 1: Go to the structure tab.
step 2: click on change tab for the column you want to auto increment. In my case, i am changing for id column.
step 3: check the AI(autoincrement ) column
And you are done!