Autoincrement through IDENTITY in SQL Server 2012 Management Studio - sql

I'm trying to do autoincrement in SQL Server 2012 Management Studio by using identity, but I'm not able to fill in values for incremental column ID. What to fill in insert values?
Part of my code looks like this:
CREATE TABLE G_Members
(
ID int(4) IDENTITY(0001, 1) PRIMARY KEY,
Jméno varchar(20) NOT NULL,
Nick varchar(20) NULL,
Příjmení varchar(20) NOT NULL,
Pohlaví char(1) NOT NULL,
Datum_Narození date NULL
);
INSERT INTO G_Members VALUES
( 'Martin', 'Mates', 'Škorník', 'M', 01-AUG-1978);
INSERT INTO G_Members VALUES
(NEXT VALUE FOR G_Members.ID, 'Ondřej', ' ', 'Panenka', 'M', 29-MAR-1983, );

If you have an Auto Increment Column you cannot insert any data for that column. You have to modify your SQL-Statement in such a way that you specify all other columns and obmit the IDENTITY column. This is achieved as follows:
INSERT INTO G_Members (Jméno,Nick,Příjmení, Pohlaví,Datum_Narození) VALUES ( 'Martin', 'Mates', 'Škorník', 'M', 01-AUG-1978);
SQL Server will insert a new value for the Id column.
Edit:
I suggest you to use nvarchar over varchar because then you will be able to store unicode values. Especially for your language this would be a better choice

Related

Constraint not working as desired for my INSERT?

I am creating a Table named "Cliente" with some constraints on it as it follows:
CREATE TABLE public."Cliente" (
"K_CODCLIENTE" numeric(5) NOT NULL,
"N_NOMBRE1" varchar(15) NOT NULL,
"N_NOMBRE2" varchar(15) NOT NULL,
"N_APELLIDO1" varchar(15) NOT NULL,
"N_APELLIDO2" varchar(15),
"N_DIRECCION" varchar(50) NOT NULL,
"Q_TELEFONO" numeric(10) NOT NULL,
"K_CODREF" numeric(5),
"I_TIPOID" varchar(2) NOT NULL,
"Q_IDENTIFICACION" varchar(10) NOT NULL,
CONSTRAINT "PK_Cliente" PRIMARY KEY ("K_CODCLIENTE"),
CONSTRAINT "UQ_ID_TIPOID_CLIENTE" UNIQUE ("I_TIPOID","Q_IDENTIFICACION"),
CONSTRAINT "CK_CODCLIENTE" CHECK ("K_CODCLIENTE" >= 100),
CONSTRAINT "CK_Q_IDENTIFICACION" CHECK ("Q_IDENTIFICACION" IN ('CC', 'PA', 'CE', 'NI', 'OT'))
);
When I try to insert some values on it:
INSERT INTO "Cliente"
VALUES ('101','Juan','Felipe','Ortiz','Rojas','AK 15 no. 28-05','3101125507',null,'CC','51111111');
I get the following error (in PostgreSQL 14, on Fedora):
[23514] ERROR: new row for relation "Cliente" violates check constraint "CK_Q_IDENTIFICACION"
Detail: Failing row contains (101, Juan, Felipe, Ortiz, Rojas, AK 15 no. 28-05, 3101125507, null, CC, 51111111).
I am trying to restrict the "Q_IDENTIFICACION" column so it can only be filled with 'CC', 'PA', 'CE, 'NI' or 'OT'.
Maybe I'm doing something wrong when declaring the constraint "CK_Q_IDENTIFICACION"?
Seems like you messed up the mapping of values and are trying to insert '51111111' to "Q_IDENTIFICACION".
Consider this more revealing variant with a formatted list of target columns:
INSERT INTO "Cliente"
("K_CODCLIENTE", "N_NOMBRE1", "N_NOMBRE2", "N_APELLIDO1", "N_APELLIDO2", "N_DIRECCION" , "Q_TELEFONO", "K_CODREF", "I_TIPOID", "Q_IDENTIFICACION")
VALUES ('101' , 'Juan' ,'Felipe' , 'Ortiz' , 'Rojas' , 'AK 15 no. 28-05', '3101125507', NULL , 'CC' , '51111111'); -- !
Maybe you want to switch the last two column names in the table definition - and (not) adapt the VALUES list in the INSERT accordingly? (varchar(2) vs. varchar(10) seems switched as well.)
For persisted code, it's generally advisable to spell out target columns in an INSERT command in any case.
Asides:
Reconsider all these pesky double-quoted upper case identifiers. See:
Are PostgreSQL column names case-sensitive?
Consider plain type text instead of varchar(n) with strikingly tight character limits. See:
Any downsides of using data type "text" for storing strings?

Correctly insert row into MS SQL Server

I have a SQL Server table created with:
IF OBJECT_ID('dbo.Messages', 'U') IS NOT NULL
DROP TABLE dbo.Messages
GO
CREATE TABLE dbo.Messages
(
Id INT NOT NULL PRIMARY KEY, -- primary key column
Username [NVARCHAR](50) NOT NULL,
MessageType [NVARCHAR](50) NOT NULL,
Recepient [NVARCHAR](50) NOT NULL,
RecepientType [NVARCHAR](50) NOT NULL,
Payload [NVARCHAR](255),
Stamp DATETIME
);
GO
When I try to insert data into the table, an error happens.
Insert statement:
INSERT INTO dbo.Messages
VALUES ('thin', 'message.broadcast', 'channelID', 'channel', 'test', '2019-07-23 15:19:08.960697828 +0300 EEST m=+14.232534538')
Column name or number of supplied values does not match table
definition.
Is this happening because my datetime needs to formatted for SQL Server, or do I need to describe the primary key differently in to order to have SQL Server autogenerate values for this column?
What would be the correct way to do this?
You are missing ID in your insert statement.
If you want ID to be autogenerated you need to use IDENTITY(1, 1) where you choose seed and increment step in place of 1's.
If you don't want to autogenerate ID, then you need to include it in INSERT statements.
Column definition should be:
Id INT IDENTITY(1, 1) PRIMARY KEY
Consider change stamp column to timestamp and id to identity column like this:
IF OBJECT_ID('dbo.Messages', 'U') IS NOT NULL
DROP TABLE dbo.Messages
GO
CREATE TABLE dbo.Messages
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY, -- primary key column
Username [NVARCHAR](50) NOT NULL,
MessageType [NVARCHAR](50) NOT NULL,
Recepient [NVARCHAR](50) NOT NULL,
RecepientType [NVARCHAR](50) NOT NULL,
Payload [NVARCHAR](255),
Stamp [timestamp] NOT NULL -- timestamp column
);
GO
Then, simply insert your data:
INSERT INTO dbo.Messages
(Username, MessageType, Recepient, RecepientType, Payload)
VALUES('thin', 'message.broadcast', 'channelID', 'channel', 'test')
Although your error clears that 6 values are passing for 7 columns.
You need to insert specifically column names.
Insert into Messages ( Username , MessageType , Recepient , RecepientType , Payload , Stamp )
values ('thin', 'message.broadcast', 'channelID', 'channel', 'test', '2019-07-23 15:19:08.960697828 +0300 EEST m=+14.232534538')
After that also you are facing an issue which is corrected by this.
If Id want to be inserted automatic, then make it idenity like Id int identity(1, 1) not null
You need to add as many columns in your insert statement as there are columns in your table, except for identity fields.
Without your Id as identity, you need this
insert into Messages (Id, Username, MessageType, Recepient, RecepientType, Payload, Stamp)
values (1, 'thin', 'message.broadcast', 'channelID', 'channel', 'test', '2019-07-23 15:19:08.960697828 +0300 EEST m=+14.232534538')
This means its up to you to determine the next value for your Id every time.
Better is to create the Id field as identity like this
Id INT IDENTITY(1, 1) PRIMARY KEY
Now you can simply do this (the Id value will be automatic incremented now)
insert into Messages (Username, MessageType, Recepient, RecepientType, Payload, Stamp)
values ('thin', 'message.broadcast', 'channelID', 'channel', 'test', '2019-07-23 15:19:08.960697828 +0300 EEST m=+14.232534538')
Using column names in your insert also has the benefit that you can put them in any order you like

Swap data in two columns using single sql query

User has entered data in wrong columns.
For example, I have a table with two columns applicant name and father name. Data operator has entered father name in applicant name column and applicant name in father name column. Please suggest a way to swap the data in both columns i.e data in applicant name column should move to father name column and data in father name column should move to applicant name column. Using single sql query
It may sounds funny, But you can easily alter the table and change the column name with correct labeling.
CREATE TABLE `swap_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`x` varchar(255) DEFAULT NULL,
`y` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `swap_test` VALUES ('1', 'a', '10');
INSERT INTO `swap_test` VALUES ('2', NULL, '20');
INSERT INTO `swap_test` VALUES ('3', 'c', NULL);
Solution would be :
UPDATE swap_test SET x=(#temp:=x), x = y, y = #temp;
More info can be found here.
You can simply assign the names
update the_table
set applicant_name = father_name,
father_name = applicant_name
where ...; -- make sure to only do that for the rows that need it
The SQL standard requires that the values used on the right side are evaluated before the assignment.
This works with every modern DBMS, but not with MySQL. See dexter's answer if you need a workaround for MySQL.
Online example: https://rextester.com/RIK34525

SQL data truncation for date value

I'm having a hard time creating a simple table:
CREATE TABLE `csat` (
`csat_id` INT NOT NULL AUTO_INCREMENT,
`value` INT,
`month` DATE NOT NULL,
PRIMARY KEY (`csat_id`)
);
CREATE TABLE `migrated` (
`migrated_id` INT NOT NULL AUTO_INCREMENT,
`title` INT,
`description` INT,
`month` DATE NOT NULL,
PRIMARY KEY (`migrated_id`)
);
INSERT INTO csat
VALUES (1, 1, 2017-06-15);
INSERT INTO migrated
VALUES (1, 2, 2018-06-15);
I get the error:
Data truncation: Incorrect date value: '1996' for column 'month' at row 1
It seems like my date is in the right format:
https://www.w3schools.com/sql/func_mysql_date.asp
I'm also wondering why I need to specify a value on the csat_id, because I thought SQL would just put that in for me since its the primary key.
You have to wrap your date values in single quotation marks: '2017-06-15', not 2017-06-15. Right now, MySQL is evaluating this as 2017 minus 6 minus 15, which comes to 1996.
Also, when inserting, it's best to specify the columns you're inserting into. And if your column is set to AUTO_INCREMENT, you don't need to specify it:
INSERT INTO csat
(`value`, `month`)
VALUES
(1, '2017-06-15');
I would also consider changing your column names. Perhaps make "value" more descriptive (value of what?) And month is misleading, since it's actually a date-type column.
You haven't said which database server you're using, but generally speaking dates are inputted as strings.
You should try the following inserts;
INSERT INTO csat (`csat_id`, `value`, `month`)
VALUES (1, 1, '2017-06-15');
INSERT INTO migrated (`migrated_id`, `title`, `description`, `month`)
VALUES (1, 2, 2, '2018-06-15');
Also, you should specify which columns you're inserting into. This prevents data from being entered into the wrong fields, especially when schema changes occur.
SQL does auto increment primary key fields (if defined that way). However, you had to define it in your insert statements because you didn't specify the columns you were inserting to.
Try this instead;
INSERT INTO csat (`value`, `month`)
VALUES (1, '2017-06-15');
INSERT INTO migrated (`title`, `description`, `month`)
VALUES (2, 2, '2018-06-15');
I guess you missed the single qoutes (as per Sql standards) at first in your date and then while inserting even if the column is autoincrement you need to specify columns other than the autoincrement column so as to make sure the data you are inserting belongs to that specific column or not
Try this
INSERT INTO
csat(value,month) values
(1,'2017-06-15')

SET datatype set in SQL Server

While creating a table I have to use the datatype SET, but it looks like there is no datatype SET in SQL Server. I was looking on the Microsoft's website and those are the datatypes that it supports: http://msdn.microsoft.com/en-us/library/ms187752.aspx
Which one should I use to replace the SET?
I have used SET in MySQL database like this:
CREATE TABLE IF NOT EXISTS `configurations` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`configDuration` int(5) NOT NULL,
`configDurationPerspective` set('list_this_day','list_remaining') NOT NULL,
PRIMARY KEY (`index`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And then when I insert data into the table it looks like this:
INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 'list_this_day');
Never mind the quotes. Something messed up while pasting the code.
Now I want to do the same thing, but in SQL Server.
You'd either have to use separate bit fields (one column with bit datatype per value) or you'd pack the values into a column with a integer datatype. If you'd use integer you'd have to use t-sql bitwise operators to read and write the values.
If you use bitwise operators you'll only get one column
The create table statement should look like this:
CREATE TABLE configurations(
[index] int NOT NULL IDENTITY (1,1) PRIMARY KEY,
user_id int NOT NULL,
configDuration int NOT NULL,
configDurationPerspective int NOT NULL,
)
And then you'd have to insert values that are possible to bitmask like 1,2,4,8,16,32 into configDurationPerspective
INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 'list_this_day');
would translate to
INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 1);
And
INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 'list_remaining');
would translate to
INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 2);
and selecting could look like:
select [index], configDuration,
case when configDurationPerspective & 1 > 0 then 'list_this_day' else '' end
+ case when configDurationPerspective & 2 > 0 then 'list_remaining' else '' end as configDurationPerspective
from configurations
The list of basic types in MS SQL Server does not support the same. But what we have are constraints and user types. In this question you can see how MySQL enum is solved
SQL Server equivalent to MySQL enum data type?
And you can also observe user types (I've seen that they were used for the similar purpose)
http://msdn.microsoft.com/en-us/library/ms175007.aspx
But as the most typical solution to this issue, we were (on our projects) using some "CodeList/StaticList" table and referencing it by Primary key (int, shortint, tinyint)