Auto Increment Composite Primary Key - sql

I have an Access database that I am trying to create. I want to use two columns from the table to create the primary key.
Projectbl (ProjectID, ProjectRegion, other columns)
I want the ProjectID to autoincrement. That's fine. So far whenever I add a new project, the ProjecID increments by itself.
I want to create a new column in that same table that will be the ProjectRef where the new number would be a composite of ProjectID and ProjectRegion.
So for example
ProjectID ProjectRegion OtherCol
---------------------------------
1 500 ...
2 100 ...
3 200 ...
4 500 ...
5 500 ...
6 100 ...
I want the table to actually look like that
ProjectRef ProjectID ProjectRegion OtherCol
--------------------------------------------
5001 1 500 ...
1002 2 100 ...
2003 3 200 ...
5004 4 500 ...
5005 5 500 ...
1006 6 100 ...
So I am trying to add a new project: the projectID will autoincrement to 7, but the ProjectRef will be 'ProjectReg'7 whatever the ProjectReg is.
I know I can create a composite key with
CREATE TABLE 'Projectbl'
(
ProjectID INT(10) NOT NULL AUTO_INCREMENT,
ProjectRegion INT(10) NOT NULL,
other columns VARCHAR(100),
CONSTRAINT ProjectRef
PRIMARY KEY ('ProjectRegion', 'ProjectID')
)
How can I actually display ProjectRef in the table?

You shouldn't have the ProjectRef column at all. This violates basic rules of database normalization. If you want your front end to display the ProjectRef then just calculate it from the columns that you have.

Related

How to update unique table row numbers before inserting new row at existing position

SQL table:
id | name
----+--------
1 | apple
2 | orange
3 | apricot
The id is primary key, unique, could be SERIES. The goal is to insert new row where id equals 2 and shift existing row numbers below, that is 2 and 3, to 3 and 4 position.
I have tried shift rows before inserting new row:
"UPDATE some_table SET id = id + 1 WHERE id >= id"
but an error occurred:
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "some_table_pkey"
Detail: Key (id)=(3) already exists.
Is there some effective way to do such an operation?
The table should look like this after update:
id | name
----+--------
1 | apple
2 | cherry
3 | orange
4 | apricot
While I think the attempt is futile, you can achieve that by marking the primary key constraint as deferrable:
CREATE TABLE some_table
(
id int,
name text
);
alter table some_table
add constraint pk_some_table
primary key (id)
deferrable initially immediate; --<< HERE
In that case the PK constraint is evaluated at per statement, not per row.
Online example: https://rextester.com/JSIV60771
update Names
set id=id+1
where id in
(select id from Names where id>=2 order by id desc);
Here first you can update the id's and then you can insert
insert into Names (id,name) values(2,'cheery')

How to insert rows and getting an incremental value if I have NOT setup IDENTITY for a column?

I have a table with a Primary Key ShopId (setted as not UNIQUE).
A script add rows with ShopId as follow (which are Primary KEY)
0
1
2
3
4
5
500
501
502
503
8
9
10
600 -- higher value
400
300
When I use an INSERT statement I want to add a new row with ShopId 601 (with auto increment).
I would like to know if it possible to do it automatically at DB level.
CREATE TABLE dbo.Shops
(ShopId int NOT NULL CONSTRAINT PK_Shops_ShopId PRIMARY KEY,
Name nvarchar(64) NOT NULL,
LocationId int NOT NULL )
From your comment, your script must just run once.
So declare your column as identity, and for your script, you can use
SET IDENTITY_INSERT db_name.table_name ON
run the script
SET IDENTITY_INSERT db_name.table_name OFF
This allows you do insert your values in an IDENTITY column.
After that, the incrementation will start with the highest value +1.
see msdn

SQL Server composite key custom Auto Increment in child field

I'm using SQL Server 2012 Express. I have created the following table
CREATE TABLE [dbo].[logis_location]
( [loc_id] int identity NOT NULL
, [loc_name] varchar(50) NOT NULL )
CREATE TABLE [dbo].[rev_bill]
( [bill_id] int identity NOT NULL ,
[loc_id] int NOT NULL )
ALTER TABLE [dbo].[rev_bill]
ADD CONSTRAINT [rev_bill_PK] PRIMARY KEY CLUSTERED ( [bill_id] , [loc_id] )
ALTER TABLE [dbo].[rev_bill] WITH CHECK
ADD CONSTRAINT [logis_location_rev_bill_FK1]
FOREIGN KEY ( [loc_id] )
THe bill_id is auto incrementing ,But bill table have composite key based on location table loc_id which is foreign Key.
This resulting following output
bill_id loc_id 1 1 2 1 3 2 4 2 5 1
6 3
7 2
However expected outcome is
bill_id loc_id
1 1
2 1
1 2
2 2
3 1
1 3
3 2
I want to increment the location specific bill_id in most safest way.It means when inserting new bill ,the bill id should be incremented ,but considering the loc_id.As given above, If there is bill for the given location (eg:loc_id =4), first bill for that location should have bill_id 1,and next one should be 2. This is Client requirement.
Please provide me some guide line.

How to re-number T-SQL's system auto-increment Identity column?

I have an auto-increment primary key in a SQL table lets say table look like this:
CREATE TABLE [Table] (--Identifier contains a space and uses a reserved keyword.
[ID] [int] IDENTITY(1,1) NOT NULL ,
[Name] [varchar](50) NULL,
CONSTRAINT [PK__Table] PRIMARY KEY CLUSTERED ([ID] ASC)
);
ID | Name|
1 John
2 Jack
3 Bill
4 Joe
Then I delete row 2 Jack:
ID | Name|
1 John
3 Bill
4 Joe
And what I want to achieve is to change id column so the table will look like this
ID | Name|
1 John
2 Bill
3 Joe
Is there a way to do it?
I will never do that but you can:
create a new autoincrement primary key named ID2
delete ID column
rename ID2 column as ID
Quick and dirty way to do it is, (my way) -->
select * into yournewtable from youroldtable order by yourIdentityColumn;
Then, open up yournewtable's design, make sure yourIdentityColumn is Identity(1,1).
Then, drop youroldtable.
Then, rename yournewtable to youroldtable! ta-da!
Set identity_insert Table off;
Update Table set ID = 3 where ID = 4;
...
Set identity_insert Table on;
Where Table name is Table

SQL : Iterate through rows and update set of rows that have same primary key

I have a table called *Provider_Compliances*
(ProviderNum,
ProviderLocation,
HistorySequence,
ProviderEffectiveDate,
PeriodBeginDate,
PeriodEndDate,
IsCompliant)
Example of data :
ProviderNum |ProviderLocatin |HistorySequence|ProviderEffectiveDate|PeriodBeginDate|PeriodEndDate|IsCompliant
1 | 1 | 2 | 2012-01-01 | 2010-01-03 | 2012-01-01 | No
2 | 2 | 2 | 2012-01-01 | 2012-01-02 | 9999-12-31 | Yes
The primary key for the Provider_Compliances Table is (ProviderNumber,HistorySequence, ProviderLocation, ProviderEffectiveDate).
I am trying to add a new columns (ComplianceNumber) and then change the primary key of the Provider_Compliances Table to composite key (ComplianceNumber, HistorySequence).
I don't want to lose any preexisting data.
So, I thought of doing it this way :
//1st, add the new column(ComplianceNumber) with default value 0
ALTER TABLE Provider_Compliances ADD ComplianceNumber DECIMAL(10) DEFAULT 0
//2nd, update all existing rows
UPDATE Provider_Compliances SET ComplianceNumber = (NEXT VALUE FOR Provider_Compliances_Sequence)
//3rd, modify the primary key
ALTER TABLE Provider_Compliances DROP PRIMARY KEY
ALTER TABLE Provider_Compliances ADD PRIMARY KEY(ComplianceNumber, HistorySequence)
The problem with step 2 is that it will set every row to a new ComplianceNumber.
I want every row that has the same ProviderNumber + ProviderLocation + ProviderEffectiveDate to be granted the same ComplianceNumber.
You will be able to do this with a SQL script as follows
Create a temp table with records group by ProviderNumber +
ProviderLocation + ProviderEffectiveDate including new column
Loop through temp table and update the new column (with incremental number - or as you needed)
Join this table with original one & do the update new column of original table with the value in temp table