Inserting a row with SQL Server Management Studio results in ERROR - sql-server

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);

Related

Table Variable with Primary and Identity Key

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.

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!

User defined table type with check constraint

I want to create a table type for use in a stored procedure, but I want to ensure that one of the parameters passed into the table is one of two values.
If I'm interpreting the documentation correctly, the only column constraint available is primary key but please correct me if I'm wrong.
Here's what I've tried:
create type dealerDisable as table
(id int not null,
dealerNo varchar(10) not null,
dealerName varchar(50),
disabling varchar(5),
constraint ratesOrAll
check (disabling in ('Rates','All')),
dateAdded date)
Here's the error I get, which isn't all that illuminating:
The syntax for creating table types is a little more restrictive - it does not support named constraints, along with some other differences compared to CREATE TABLE.
CREATE TYPE dbo.dealerDisable AS TABLE -- ALWAYS use schema!
(
id int not null,
dealerNo varchar(10) not null,
dealerName varchar(50),
disabling varchar(5) check (disabling in ('Rates','All')),
dateAdded date
);
When you try to insert a value, you can see that the system had to create a unique constraint name for each instance of the table:
DECLARE #d dbo.dealerDisable2;
INSERT #d VALUES(1,'blat','foo','None',getdate());
DECLARE #e dbo.dealerDisable2;
INSERT #e VALUES(1,'blat','foo','None',getdate());
Errors:
Msg 547, Level 16, State 0
The INSERT statement conflicted with the CHECK constraint "CK__#BCAA5D0E__disab__BD9E8147".
...
Msg 547, Level 16, State 0
The INSERT statement conflicted with the CHECK constraint "CK__#AAF87C65__disab__ABECA09E".
...
If you think about the mechanism behind this, it makes sense. For some types of constraints, you can only have one in the database with the same name. This would yield the same type of error, for example:
CREATE TABLE #a(id int, CONSTRAINT PK1 PRIMARY KEY (id));
CREATE TABLE #b(id int, CONSTRAINT PK1 PRIMARY KEY (id));
Now, while it's true that you can have as many check constraints with the same name as you like, this is probably just a blunt simplification of the syntax.
Please refer to Documentation. The correct syntax should be as below. Without the CONSTRAINT keyword
create type dealerDisable as table
(
id int not null,
dealerNo varchar(10) not null,
dealerName varchar(50),
disabling varchar(5),
check (disabling in ('Rates','All')),
dateAdded date
)

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

Autoincrement of primary key column with varchar datatype in it

CREATE TABLE Persons
(
P_Id varchar(6) NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)
in this table P_Id is the primary key. We want to generate autoincrement of P_Id with default value (PN00) in the start while inserting only LastName and FirstName .eg :-PN001 for first entry ,PN002 for second,PN003 for third and so on .
The only viable solution is to use
an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.Persons
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
P_ID AS 'PN' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into Persons without specifying values for ID or P_ID:
INSERT INTO dbo.Persons(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and P_Id will contain values like PN00001, PN00002,...... and so on - automatically, safely, reliably, no duplicates.
There are different ways to address your issue.
You could use a Trigger.Triggers are activated on some events. You could create a trigger for 'Instead of Insert On Persons' event. When the event is triggered, then generate a new P_Id. Insert this new P_Id alongwith all the values as the new record for your table.
This approach wont have coupling with the table's schema.
Refer this link for more information on Triggers :
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
Refer this link to emulate 'before insert trigger' in SQL Server:
How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritence) entities?
You could also use a Procedure like :
create procedure Persons_insert(#lastname varchar(255), #firstname varchar(255))
as
begin
--write code to generate the ID as you like
insert into Persons(p_id,lastname,firstname)values(generated_id,lastname,firstname);
end

Resources