Consider a table like this one (postgresql):
create table t1 (
id serial not null primary key,
code1 int not null,
company_id int not null
);
create unique index idx1 on t1(code1, company_id);
I have to a new column code2 that will be not null and with a unique index like idx1, so the migration could be like:
alter table t1 add column code2 int not null;
create unique index idx2 on t1(code2, company_id);
The problem is: how do you manage the migration with the data that are already in the table?
You cannot apply this migration neither I can define a default value for the column.
What I was thinking to do is:
create and execute migration that just add the column without any constraint
insert the data manually in the column not with a migration
create and execute another migration that adds the constraints to the column
Is this a good practice or there are other ways?
As migration tool I am using flyway but I think it's the same for every database migration tool.
I have a table defined in Sql Server with a GUID primary key and a default of newsequentialid():
CREATE TABLE [dbo].[mything](
[id] [uniqueidentifier] NOT NULL,
[foo] [varchar][32] NULL,
CONSTRAINT [PK_mything] PRIMARY KEY CLUSTERED
(
[id] ASC
)
)
GO
ALTER TABLE [dbo].[mything]
ADD CONSTRAINT [DF_mything_id]
DEFAULT (newsequentialid()) FOR [id]
GO
And when I add an entity with the guid primary key already set, it ends up as a record in the database with a new guid primary key.
var anEntity = new mything
{
id = "17870C25-FC04-EB11-80E9-000C29F38B54",
foo = "Some stuff",
}
dbContext.mythings.Add(anEntity);
dbContext.SaveChanges();
EF seems to ignore the guid that was provided in the record and writes the record with a new Guid.
What I would expect is that the record provided had a null guid, it would be populated with a new guid, and if it was not null it would be used unchanged. But that's not what I'm seeing happen.
I'm seeing duplicate records, with different GUIDs, instead of primary key violation exceptions, because the GUIDs I'm providing in my EF entities are being ignored.
Why could this be happening?
Please tell me this isn't by design!
===
OK, this does seem to be by design.
First, this isn't in SQL server. If I try to insert a record with the id field set, it inserts, or fails with a primary key failure if there is already a record with that id. It only creates a new GUID for the id field if the provided id field is null.
But in EF, the value in the id field is ignored, and a new GUID is generated every time.
It was suggested to me that EF was behaving this way so as to follow the same pattern as when using autoincrement keys. And that does seem to be the case.
In SQL Server, if you try to provide a value to an autoincrement key field on an insert, you get an error:
Cannot insert explicit value for identity column in table
But in EF, the value you provide is ignored, and a new value is generated.
So in this respect, Entity Framework is consistent. Consistently wrong, but consistent.
First step I'd look at to narrow this down is to capture a Profiler/Extended Event trace at the database to see exactly what EF is sending to the database.
Your expectation of the database behaviour is correct - so I'd want to understand where it is breaking down first
I'm application switching databases for my application from MySQL to SQLServer.
Today I implement a custom id generation strategy defined in an abstract class all POJOs use. This works, but I am only able to generate an id via the application.
With this database migration, I'd like, after creating the schema, define somewhere all the 'id' columns for all tables to use a procedure that returns a SELECT NEWID(); query.
Is this possible? How?
I like to define the ID columns with a default constraint:
create table a
(
id
uniqueidentifier not null
constraint [a.id.default.newid]
default( newid() )
constraint [a.id.primarykey]
primary key clustered,
--> other columns...
)
This way, you can either take an app-generated ID or let the database assign it, depending on your needs. Your primary key constraint (or unique constraint) enforces uniqueness...which is important if you allow incoming IDs from the apps.
In the scripts...where you don't necessarily have the need to generate the ID, don't specify a value...and the default kicks in. You can insert newid(), too...
insert a
select newid()
from b
...and SQL Server knows to call newid() for each row
How do I auto increment the primary key in a SQL Server database table? I've had a look through the forum but can't see how to do this.
I've looked at the properties but can't see an option. I saw an answer where you go to the Identity specification property and set it to yes and set the Identity increment to 1, but that section is grayed out and I can't change the no to yes.
There must be a simple way to do this but I can't find it.
Make sure that the Key column's datatype is int and then setting identity manually, as image shows
Or just run this code
-- ID is the name of the [to be] identity column
ALTER TABLE [yourTable] DROP COLUMN ID
ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)
the code will run, if ID is not the only column in the table
image reference fifo's
When you're creating the table, you can create an IDENTITY column as follows:
CREATE TABLE (
ID_column INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
...
);
The IDENTITY property will auto-increment the column up from number 1. (Note that the data type of the column has to be an integer.) If you want to add this to an existing column, use an ALTER TABLE command.
Edit:
Tested a bit, and I can't find a way to change the Identity properties via the Column Properties window for various tables. I guess if you want to make a column an identity column, you HAVE to use an ALTER TABLE command.
You have to expand the Identity section to expose increment and seed.
Edit: I assumed that you'd have an integer datatype, not char(10). Which is reasonable I'd say and valid when I posted this answer
Expand your database, expand your table right click on your table and select design from dropdown.
Now go Column properties below of it scroll down and find Identity Specification, expand it and you will find Is Identity make it Yes. Now choose Identity Increment right below of it give the value you want to increment in it.
CREATE TABLE Persons (
Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid" column (a unique value will be added automatically):
Perhaps I'm missing something but why doesn't this work with the SEQUENCE object? Is this not what you're looking for?
Example:
CREATE SCHEMA blah.
GO
CREATE SEQUENCE blah.blahsequence
START WITH 1
INCREMENT BY 1
NO CYCLE;
CREATE TABLE blah.de_blah_blah
(numbers bigint PRIMARY KEY NOT NULL
......etc
When referencing the squence in say an INSERT command just use:
NEXT VALUE FOR blah.blahsequence
More information and options for SEQUENCE
When you're using Data Type: int you can select the row which you want to get autoincremented and go to the column properties tag. There you can set the identity to 'yes'. The starting value for autoincrement can also be edited there. Hope I could help ;)
I had this issue where I had already created the table and could not change it without dropping the table so what I did was:
(Not sure when they implemented this but had it in SQL 2016)
Right click on the table in the Object Explorer:
Script Table as > DROP And CREATE To > New Query Editor Window
Then do the edit to the script said by Josien; scroll to the bottom where the CREATE TABLE is, find your Primary Key and append IDENTITY(1,1) to the end before the comma. Run script.
The DROP and CREATE script was also helpful for me because of this issue. (Which the generated script handles.)
You can use the keyword IDENTITY as the data type to the column along with PRIMARY KEY constraint when creating the table.
ex:
StudentNumber IDENTITY(1,1) PRIMARY KEY
In here the first '1' means the starting value and the second '1' is the incrementing value.
If the table is already populated it is not possible to change a column to IDENTITY column or convert it to non IDENTITY column. You would need to export all the data out then you can change column type to IDENTITY or vice versa and then import data back.
I know it is painful process but I believe there is no alternative except for using sequence as mentioned in this post.
Be carefull like if you want the ID elements to be contigius or not. As SQLSERVER ID can jump by 1000 .
Examle: before restart ID=11
after restart , you insert new row in the table, then the id will be 1012.
You could do the following: New Table Creation:
-- create new table with Column ID which is Primary Key and Auto Increment --
CREATE TABLE titles(
id INT NOT NULL IDENTITY(1,1) PRIMARY KEY, --Primary Key with Auto-Increment --
keyword VARCHAR(260),
status VARCHAR(10),
);
If you Table Already exists and need to make the changes to ID column to be auto-increment and Primary key, then see below:
ALTER TABLE table DROP COLUMN id; // drop the existing ID in the table
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key
Imagine I have a table with 3 columns:
ID (unique ID)
Description (varchar 2000)
IsDeleted (boolean)
I want to add a unique constraint so that all descriptions are unique. BUT only for active records i.e. IsDelete = false. If a user flags a record as deleted, they can re-add a record with the same description as a deleted record, but not the same as a active record.
So, I only want the constraint to effect record where IsDeleted = false.
Tim
In SQL 2008 you can do this using unique index with a filter:
CREATE UNIQUE NONCLUSTERED INDEX ix_table_UNC ON table(Description) WHERE IsDeleted = 0
Pre-SQL 2008, you'd need to create the unique index on a view of the table selecting only the non-deleted records:
CREATE VIEW dbo.vw_ActiveDescriptions WITH SCHEMABINDING
AS
SELECT Id, Description
FROM Table
WHERE IsDeleted= 0
GO
CREATE UNIQUE CLUSTERED INDEX ix_vw_ActiveDescriptions_UC ON dbo.vw_ActiveDescriptions(Description);
Create a new table for the deleted rows. Then enforce uniqueness with a UNIQUE constraint. You would have to make Description smaller because the maximum key size in SQL Server is 900 bytes.