Msg 207, Level 16, Invalid column name 'MH380' - sql-server

I got an error from the insert statement.
The statement that I used to insert a tuple into the table is
insert into train values (103, MH380, 2000, 709)
By the way, the table was created by using the statement below:
(
TrainCode CHAR(5) NOT NULL,
TrainName VARCHAR(20) NOT NULL,
Capacity int NOT NULL,
Model VARCHAR(20) NOT NULL,
CONSTRAINT PKTrain PRIMARY KEY (TrainCode)
)
Can someone please help? TQ

MH380 appears to be a string, so you need to surround it in single quotes.
insert into train values (103, 'MH380', 2000, 709)
You may also want to check the other values too - they appear numeric but if you've declared their corresponding column types as chars or varchars (e.g. the train code?), you should really cast them as such by putting quotes around them too.
Also you might want to think about putting your column names into your INSERT statement, so the order of fields is explicit rather than implicit. Could save headaches later if your table gets altered!

Per your posted table structure as below
(TrainCode CHAR(5) NOT NULL, TrainName VARCHAR(20) NOT NULL, Capacity int
NOT NULL,Model VARCHAR(20) NOT NULL, CONSTRAINT PKTrain PRIMARY KEY (TrainCode) )
Correct INSERT statement should be like below since except Capacity all other columns are of VARCHAR type.
insert into train values ('103', 'MH380', 2000, '709')

Related

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
)

INSERT INTO, but retain blank columns?

In a stored procedure I'm creating...
IF OBJECT_ID('tempdb..##SUBOSummary') IS NOT NULL
/*Then it exists*/
DROP TABLE ##SUBOSummary
CREATE TABLE ##SUBOSummary
(
--RowID int not null identity(1,1) primary key,
RowNum int IDENTITY(1,1) NOT NULL,
Dept nvarchar(25) NOT NULL,
Last24 int,
WTD int,
MoTD int,
YTD int
)
I then want to add a series of data from another view, and I'll then fill the rest of the data rows in seperately:
INSERT INTO ##SUBOSummary SELECT DISTINCT vw_EmployeeDepartment.Dept FROM vw_EmployeeDepartment
I'm getting the following error:
Column name or number of supplied values does not match table definition.
I'm hazarding a guess that this is because I'm only populating a single field by the insert statement.
Is there a better way to acheive this?
The error, in truth, is quite clear here:
Column name or number of supplied values does not match table definition.
In your INSERT statement you're implying you want to insert values into all the columns (as you're not specifying which one), yet you're only supplying one column in your SELECT, so where does that value go? SQL Server has no idea.
You need to supply your column(s) in your INSERT clause:
INSERT INTO ##SUBOSummary (Dept)
SELECT DISTINCT vw_EmployeeDepartment.Dept
FROM vw_EmployeeDepartment;
On a different note, however, don't use a Global Temporary Table, they often perform very poorly.

Using Sequences with SQL Server

I am trying to create a sequence with a table MiCliente the sequence must be eliminate if this exist, must be one by one and with a cycle and it needs to start with 1000. I need to associate the sequence with a column MiCliente.idCliente.
CREATE TABLE dbo.MiCliente
(
idCliente int NOT NULL,
idMunicipio int NOT NULL,
cedula varchar(20) NOT NULL,
nombres varchar(100) NOT NULL,
apellidos varchar(100) NOT NULL,
idSexo char(1) NULL,
idEstadoCivil tinyint NULL,
fechaNacimiento date NULL,
telefono varchar(20) NULL,
celular varchar(20) NULL,
direccion varchar(100) NULL,
email varchar(100) NULL
);
GO
Create Sequence Conteo
AS tinyint
START WITH 1000
INCREMENT BY 1
GO
When I execute the query I receive
error 343
I think maybe an identity field would solve your problem best. You can't really associate a sequence with a table field; at least not by definition. A sequence can be used as a type of "counter" object and can be invoked for a table to generate a value that gets inserted into a table.
(here is a good discussion on using sequences:
https://www.simple-talk.com/sql/learn-sql-server/sql-server-sequence-basics/)
For example, using the sequence you created in your example (keep in mind, as ZLK comments, tinyint is for values from 0 to 255; you should use int) one could say:
select (next value for Conteo) idCliente, cedula, email from dbo.MiCliente;
or something like
INSERT INTO MiCliente
(idCliente, idMunicipio, cedula, nombres, apellidos)
VALUES
(NEXT VALUE FOR Conteo, 1,'test','Smith','test2');
So this works, but one could reference the same sequence for another table as well. So it isn't specifically "tied" to your table. It may not matter though.
On the other hand, you could set idCliente as an identity field such that it also begins with 1000. This is "tied" to the table and, in my opinion, is easier to use. The number just get generated automatically.
So you might do something like:
Alter table dbo.MiCliente add idCliente INT IDENTITY(1000,1)
And then you can make it your primary key as well:
alter table dbo.MiCliente add constraint PK_MiCliente PRIMARY KEY(idCliente)
When I executed your query it simply gives following error:
Msg 11708, Level 16, State 1, Line 2
An invalid value was specified for argument 'START WITH' for the given data type.
It is clearly evident of the fact that you are using wrong data type tinyint while creating the sequence. Changing it to int should solve your problem. Here is the modified query. Hope this helps!
Create Sequence Conteo
AS int
START WITH 1000
INCREMENT BY 1
GO
I was able to create the sequence successfully after making this change. I'm on SQL Server 2012.

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

Auto increment a bigint column?

I want a bigint ID column for every row of data that i insert into a table. I want Sql server to generate the numbers. I tried to create a table with a bigint column ID. I want this to be autoincrement with the first value as 1. I tried using [ID] [bigint] AUTO_INCREMENT NOT NULL, in my create table statement, but I got the error - Incorrect syntax near 'AUTO_INCREMENT'. How do I do this ?
Can you not just declare it as an IDENTITY column:
[ID] [bigint] IDENTITY(1,1) NOT NULL;
The 1,1 refers to the start index and the amount it is being incremented by.
NOTE: You do not have to provide a value for the ID column when you do an insert. It will automatically choose it. You can modify these values later if required.
EDIT:
Alternatively, you can use a stored procedure to handle all the inserts.
Example:
Stored Procedure will take in variables as you would a normal insert (one variable for every column). The logic within the stored procedure can select the max value currently existing in the table and choose that as its max value.
DECLARE #yourVariable = SELECT MAX(ID) FROM YourTable
Use #yourVariable as your insert value. You can increment it or change value as necessary.
I got the answer here - http://www.sqlservercentral.com/Forums/Topic1512425-149-1.aspx
CREATE TABLE Test (
ID BIGINT IDENTITY NOT NULL,
SomeOtherColumn char(1)
)
INSERT INTO Test (SomeOtherColumn)
values ('a')

Resources