Table Variable with Primary and Identity Key - sql-server

I'm trying to enter a table variable with a primary key and identity key but I keep getting error "Msg 8101, Level 16, State 1, Line 313
An explicit value for the identity column in table '#Table4' can only be specified when a column list is used and IDENTITY_INSERT is ON."
Example of Code:
DECLARE #Table4 TABLE (ProductID INT PRIMARY KEY IDENTITY (1,1)
,DocumentNode VARCHAR(50)
,ModifiedDate DATE)
INSERT INTO #Table4
SELECT ProductID, DocumentNode, ModifiedDate
FROM [Production].[ProductDocument]
SELECT *
FROM #Table4

Your problem is that you are specifying that ProductID is an identity column and then trying to insert a ProductID value. Remove IDENTITY(1,1) for it to work.

Related

Can I auto-increment the Foreign Key column in my db table so that it matches the main table's auto-incrementing Primary Key column in SQL Server?

Create statement for my first table: 'users':
CREATE TABLE users
(
uid INT NOT NULL IDENTITY PRIMARY KEY,
firstName VARCHAR(50) NOT NULL,
lastName VARCHAR(50) NOT NULL,
middle VARCHAR(50) NOT NULL,
ssn VARCHAR(12) NOT NULL,
dob DATE NOT NULL,
phone VARCHAR(10) NOT NULL,
email VARCHAR(255) NOT NULL
)
Create statement for my second table: 'ds':
CREATE TABLE ds
(
dsu VARCHAR(50) NOT NULL,
dsp VARCHAR(50) NOT NULL,
dsImage VARCHAR(50) NOT NULL,
dsid INT NOT NULL,
Name nvarchar(50),
CONSTRAINT PK_dsid
PRIMARY KEY NONCLUSTERED (dsid),
CONSTRAINT FK_users_uid
FOREIGN KEY (dsid) REFERENCES users (uid)
ON DELETE CASCADE
ON UPDATE CASCADE
);
The first table's uid column will auto-increment with each new row I insert. I want to setup the ds table's dsid column value in each new row to automatically update to match the users table uid column value.
When I try to INSERT INTO values into the ds table:
INSERT INTO ds (dsu, dsp, dsImage)
VALUES ('john.smith', '1234567', 'Tiger')
I get the following error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'dsid', table 'company.dbo.ds'; column does not allow nulls. INSERT fails.
So, I'm trying to figure out if I'm setting up the primary key and foreign key create statements correctly to achieve the desired result, and also why I'm getting the error, and if I'm even approaching this task/problem correctly.
Any help is greatly appreciated, thank you!

Error while inserting data with stored procedure in table with shared identity primary key

I've got a few tables linked together where data should be inserted to using a stored procedure. The tables are:
create table contactpersoon
(
contactpersoonnr integer identity(1,1),
klantnr integer,
naam varchar(50) not null,
telefoonnr varchar(10) not null,
emailadres varchar(50) not null,
constraint pk_contactpersoon
primary key(contactpersoonnr, klantnr),
constraint fk_contactpersoon_klantnr
foreign key(klantnr) references klant(klantnr)
)
create table klant
(
klantnr integer identity(1,1) primary key,
bedrijfsnaam varchar(50) not null
)
create table Logins
(
GebruikersNaam varchar(30),
Wachtwoord varchar(30),
Klantnr int,
MdwNr int,
constraint pk_logID primary key(GebruikersNaam),
constraint fk_klantnr foreign key(klantnr) references klant(klantnr),
constraint fk_mdwnr foreign key(mdwnr) references medewerker(mdwnr)
)
Stored procedure for adding data to these tables:
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'spKlantAanmaken')
DROP PROCEDURE spKlantAanmaken
GO
Create Procedure spKlantAanmaken
(
#bedrijfsnaam as varchar(255),
#contactnaam as varchar(255),
#telnr as integer,
#email as varchar(255),
#gebruikersnaam as varchar(255),
#wachtwoord as varchar(255)
)
AS
Begin transaction
Declare #klantnr integer
Declare #contactpersoonnr integer
Insert into Klant Values (#klantnr, #bedrijfsnaam);
Insert into contactpersoon values(#contactpersoonnr, #klantnr, #contactnaam, #telnr, #email);
Insert into Logins values (#gebruikersnaam, #wachtwoord ,#klantnr, NULL);
Select * from contactpersoon
IF ##ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error tijdens uitvoeren van stap 2.', 16, 1)
RETURN
END
COMMIT
GO
I don't know if it is necessary to use these identity values in the inserts.
If I try this stored procedure I get the following error:
Msg 8101, Level 16, State 1, Procedure spKlantAanmaken, Line 923
An explicit value for the identity column in table 'Klant' can only be
specified when a column list is used and IDENTITY_INSERT is ON.
If I remove the identity values from the insert I get this error:
Msg 213, Level 16, State 1, Procedure spKlantAanmaken, Line 923
Column name or number of supplied values does not match table definition.
What am I doing wrong?
When you use Identity, the columns on which the identity is applied need not be in your INSERT statement VALUES. So edit your code like below
EDIT
It also seems you are missing out the columns you are trying to insert into
Insert into Klant (bedrijfsnaam) Values (#bedrijfsnaam)
Insert into contactpersoon (klantnr, contactnaam, telnr, email) Values (#klantnr, #contactnaam, #telnr, #email)
It seems all the answers saying the same thing so hope your issued is solved
Since you have identity columns, you must specify the list of columns to insert into, in your INSERT statement, and not supply a value for the identity column - like this:
Instead of
Insert into Klant Values (#klantnr, #bedrijfsnaam);
use
Insert into Klant(bedrijfsnaam) Values (#bedrijfsnaam);
and do this for all your INSERT operations.
This is a generally accepted "Best Practice" for any time you insert something into a table - it is recommend to always explicitly specify the list of columns in your table that you're inserting into (to avoid annoying errors and surprises).
Avoid the identity columns klantnr, contactpersoonnr in the INSERT query and explicitly define your column names:
So the below code will work in your case:
Insert into Klant(bedrijfsnaam) Values (#bedrijfsnaam);
Insert into contactpersoon(klantnr, naam, telefoonnr, emailadres) values(#klantnr, #contactnaam, #telnr, #email);
Just specify the column names AND the contents in the INSERT statement like:
INSERT INTO klant (bedrijfsnaam) VALUES ('XYZ');
If you don't specify the column name list, the SQL interpreter implies, you want the identity column, too. In this case you would want to set data for 2 columns, but only provide one content element, which explains the latter error message.
Edit these two lines in your SP
Insert into Klant (bedrijfsnaam)
Values (#bedrijfsnaam);
Insert into contactpersoon(klantnr,naam,telefoonnr,emailadres)
values(#klantnr, #contactnaam, #telnr, #email);
Provide a column list, excluding the identity columns in the insert statements

How to set identity constraint on existing column if data already exists in table - sybase ase 15.5

I have a table which already consists a number of records. The table has a column named 'id' of integer type and I have already inserted unique values in id column for all the records in the table.
Now I need to set IDENTITY constraint on the 'id' column so that in any new record added to the table, the value of id column gets inserted automatically incremented from the last value added to the column.
The create table query of the table is like follows:
create table Table1 (
Column1 varchar(255) not null,
Column2 varchar(254) not null,
Column3 int not null,
id int ,
PRIMARY KEY CLUSTERED ( id ) on 'default'
)
I insert data into the table using following query:
Insert into Table1 (Column1, Column2, Column3, id) values("abc","def",12,1)
But when I try to execute following Alter table query on my sybase database it returns an error "Incorrect Syntax near 'IDENTITY'"
ALTER TABLE Table1 MODIFY id int IDENTITY DEFAULT AUTOINCREMENT NOT NULL
Can anyone point me in the right direction about, how to apply IDENTITY constraint on a column which already has data?

Using SCOPE_IDENTITY() in a constraint

I am aware that using IDENT_CURRENT will not always return me the correct identity value (especially true in multi-threaded applications). I wanted to use SCOPE_IDENTITY() instead.
For example this is my Employee table:
create table Employee
(
ID int identity(1,1),
Name varchar(20),
SystemID int,
constraint Employee_PK primary key (ID asc)
)
I have a statement below:
alter table Employee
add constraint Employee_D1 default ident_current('Employee') for SystemID
which I need to modify to use SCOPE_IDENTITY() instead.
I tried the below:
alter table Employee
add constraint Employee_D1 default SCOPE_IDENITITY() for SystemID
This did not give any errors. But upon inserting a row, I did not see this column getting updated with the identity value. What am I doing wrong?
Note that the SystemID must not be readonly, so computed field isn't an option.
My exercise here is to try eliminating entry of wrong IDENTITY value in SystemID in case parallel processes try to insert rows.
Just re-read your answer. SystemID isn't an identity column. I don't think you can use SCOPE_IDENITITY() as it hasn't added the row and retrieved the new Identity value at the point it would need the value to save.
What you will need to do is create a trigger After Insert of the row to update the SystemId value. CREATE TRIGGER
Here's how I'd approach this problem (apologies for the poor field names, I'm not feeling inventive)
CREATE TABLE employees (
id int identity(1,1) NOT NULL
, name varchar(20) NOT NULL
, actual_system_id int NULL
, system_id As Coalesce(actual_system_id, id)
, CONSTRAINT pk_employees PRIMARY KEY (id)
)
;
INSERT INTO employees (name)
VALUES ('John')
, ('Paul')
, ('George')
, ('Ringo')
;
SELECT id
, name
, system_id
FROM employees
;
UPDATE employees
SET actual_system_id = 937
WHERE name = 'George'
;
SELECT id
, name
, system_id
FROM employees
;

Inserting a row with SQL Server Management Studio results in ERROR

This is what I have
CREATE TABLE Saver(
SaverID INT NOT NULL PRIMARY KEY IDENTITY,
FirstName VARCHAR(10),
Surname VARCHAR(10),
[Address] VARCHAR(60),
Email VARCHAR(30),
Username VARCHAR(10),
[Password] VARCHAR(10),
CreditBalance INT,
);
I'm trying to insert data into my table with this:
INSERT INTO Customer
(SaverID,FirstName,Surname,[Address],Email,Username,[Password],CreditBalance)
VALUES (01,'David','Slavic','123 fake street','David#gmail.com','DJ','passcode',10.00);
I get this error:
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'Customer' when IDENTITY_INSERT is set to OFF.
I don't understand why? Please help
You should not insert value for SaverID, you have told the RDBMS to generate a value for it (you've done so with your CREATE statement): SaverID INT NOT NULL PRIMARY KEY IDENTITY.
Your primary key is auto increment, you can not insert a value on it
Omit the ID from your INSERT query:
INSERT INTO Customer
(FirstName,Surname,[Address],Email,Username,[Password],CreditBalance)
VALUES ('David','Slavic','123 fake street','David#gmail.com','DJ','passcode',10.00);

Resources