Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I tried to create a table which has got 2 primary key and both of them supposed to be auto incremental by changing the Identity specification but in the property window the option (I just mentioned) is disable and I cannot change that.
The column I want to change to auto increment is the primary key of the table and type of it is INT.
What's wrong ? or What I'm wrong ?
As mentioned by TT, you can only have a single identity column and only a single primary key in a table.
For SQL Server 2012 and above, You can however use a SEQUENCE if you need 2 or more auto increment columns. You can then create a PRIMARY KEY on IDENTITY column and a UNIQUE constraint on the column with sequence as default
CREATE SEQUENCE mainseq START WITH 1 INCREMENT BY 1 ;
GO
create table table1 (
id1 int IDENTITY(1,1) NOT NULL PRIMARY KEY,
id2 bigint not null constraint DF_table1_id2 default next value for mainseq,
data varchar(20) not null
)
GO
INSERT INTO table1(data) VALUES('row 1');
INSERT INTO table1(data) VALUES('row 2');
SELECT * FROM table1;
Note that the column with sequence default behaves in differently than an identity. you cannot directly insert into an identity column (except when identity_insert is on) however you can manually insert / update the column being defaulted by a sequence.
From the definition of IDENTITY in SQL Server, you can read that a table can only have one IDENTITY column. See remarks, quote:
Only one identity column can be created per table.
I also wonder how you get two primary keys on a table, as that is not possible. See the following article on creating primary keys, quote from Limitations and Restrictions:
A table can contain only one PRIMARY KEY constraint.
If you need an additional auto incrementing column you could add a trigger to the table FOR INSERT. Something that would find the current maximum value and then add one to it.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I want to make auto increment here with the table creation but it gives an error. The database is an oracle database. The SQL is shown below.
CREATE TABLE Continents
(
ConId INT GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) PRIMARY KEY,
Continent VARCHAR(25),
);
Just remove this part
(START WITH 1, INCREMENT BY 1)
Use this syntax.
CREATE TABLE Continents
(
ConId INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
Continent VARCHAR(25),
);
The value of ConId will start at 1 (one) and always increment by one.
Refer to this db<>fiddle
Also refer to Oracle documentation1
The following statement creates a table t1 with an identity column id. The sequence generator will always assign increasing integer values to id, starting with 1.
CREATE TABLE t1 (id NUMBER GENERATED AS IDENTITY);
1SQL Language Reference (Oracle 21c) - CREATE TABLE
I need to add a new column and make it the primary key in SQL Server; the table in question does not yet have a unique key column.
Here is the sample table http://www.sqlfiddle.com/#!18/8a161/1/0
My goal is simply to have a column ID and insert values from 1 to 1160 (total number of records in this table) and make that the primary key. Also is there a way to automatically add the numbers from 1-1160 without adding each record one by one since there are 1000+ rows in this table?
Thank you!
Simply alter the table and add the column with the appropriate characteristics.
alter table x add id smallint identity(1,1) not null primary key;
Thrown together quickly and you probably should get in the habit of naming constraints. fiddle. I will note that you may or may not want to use an identity column - think carefully about your actual goal and how you want to continue using this table after the alteration.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have a table in SQL Server 2008 - let's call the table MyTable. The table has a column named Status, which is not a computed column, and is defined as varchar(40) and it allows NULLs; however, there is also a DEFAULT CONSTRAINT on this column, with the default value = 'POOL'. I just added a computed column to the table, using the following:
ALTER TABLE MyTable
ADD PrimaryStatus AS
CASE
WHEN Status LIKE '%/%' THEN LEFT(Status,CHARINDEX('/', Status) - 1)
ELSE Status
END PERSISTED
If I insert records into the table one by one (and let Status default to 'POOL' using the constraint) it works just fine; for instance, this SQL statement has no problem:
INSERT INTO MyTable (Name) VALUES ('Foo')
With the above SQL, I end up with a new record in the table with Name = 'Foo' and Status = 'POOL' and PrimaryStatus = 'POOL'
But if I execute a multi-row INSERT like the following:
INSERT INTO MyTable (Name) VALUES ('Foo'),('Bar')
then it throws an error:
Msg 537, Level 16, State 2, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.
If I drop either the default constraint or the computed column (or both), the multi-row INSERT works fine; but for some reason having both the constraint and the computed column are causing the multi-row INSERT to fail. I have tried tweaking the computed column in a variety of ways to account for NULLs (even though I don't think it should matter given the order of evaluation), but nothing seems to remedy the problem.
Anybody ever seen something like this before?
I tried to replicate the error. But, I don't get any error. I could have added this as a comment, but don't have enough points yet. Anyway, this is what i did -
CREATE TABLE [dbo].[MyTable](
[Name] [varchar](50) NULL,
[Status] [varchar](50) NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[MyTable] ADD CONSTRAINT [DF_MyTable_Status]
DEFAULT ('POOL') FOR [Status]
GO
Then i removed an extra ) in your code and did -
ALTER TABLE MyTable ADD PrimaryStatus AS
CASE WHEN Status LIKE '%/%' THEN LEFT(Status,CHARINDEX('/',Status)-1)
ELSE Status END PERSISTED
Followed by -
INSERT INTO MyTable (Name) VALUES ('Foo')
INSERT INTO MyTable (Name) VALUES ('Foo'),('Bar')
It works. Am I missing something ?
I am using SQL Server 2012 and need to add a column with a unique primary key. I am about to load several hundred thousand records BULK and just discovered repetition in the field I was going to use. Have seen SEQUENCE and GUID. Need some guidance on the best choice and how to go about setting this up so that the key field is populated during the bulk load.
When you create your table in which you want to insert information create an IDENTITY column. That will serve as an auto-populating column with a unique number for each record.
Here is a link that might help you.
If you have already created your table just change this query to what suits to your table name and run it in order to add the new column you requested.
ALTER TABLE mytable
ADD COLUMN unique_id IDENTITY (1,1)
Just a slight update on what’s already posted that includes details for adding primary key constraint
alter table database.schema.table_t
add ID_column int identity(1,1)
primary key (ID_column)
If you already set the primary key on this table just go and remove it before you execute this statement.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I create unique constraint that also allows nulls in sql server
I have a table where I need to force a column to have unique values.
This column must be nullable and by business logic multiple NULL values should be permitted, whereas other duplicate values are not.
SQL Server UNIQUE constraint is no good in this situation because it considers NULL as regular values, so it will reject duplicate NULLs.
Currently, value uniqueness is granted by the BLL so I'm not looking for a dirty hack to make it work.
I just would like to know if there is a clean solution to enforce this constraint in the DB.
And yeah, I know I can write a trigger to do that: is a trigger the only solution? (or the best solution anyway?)
If you're using SQL Server 2008 (won't work for earlier version) there is the concept of a filtered index. You can create the index on a filtered subset of the table.
CREATE UNIQUE INDEX indexName ON tableName(columns) INCLUDE includeColumns
WHERE columnName IS NOT NULL
Duplicate of this question?
The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:
CREATE TABLE dupNulls (
pk int identity(1,1) primary key,
X int NULL,
nullbuster as (case when X is null then pk else 0 end),
CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)
)
Works on SQL Server 2000. You may need ARITHABORT on e.g.
ALTER DATABASE MyDatabase SET ARITHABORT ON
If you're using SQL Server 2008, have a look into Filtered Indexes to achieve what you want.
For older version of SQL Server, a possible alternative to a trigger involves a computed column:
Create a computed column which uses the value of your "unique" column if it's not NULL, otherwise it uses the value of the row's Primary Key column (or any column which will be unique).
Apply a UNIQUE constraint to the computed column.
http://www.sqlmag.com/article/articleid/98678/sql_server_blog_98678.html
will work only in Microsoft SQL Server 2008
You can create a view in which you select only not null values and create an index on it.
Here is the source - Creating Indexed Views
You should use UNIQUEIDENTIFIER in that column, can be NULL and also is unique by definition.
Hope that helps.