Insert into first row when the table has a primary key set - sql

I spent all day creating then manually inserting into some tables I created today that look like this:
ID - Int (Primary Key set to Auto Increment)
Value - Varchar
But then I realized I had forgotten to insert a value of "--" into the first row of each table.
Is it possible to maybe add 1 to the ID no for each of the values currently in the table then insert the "--" value into the first row?

One of the ways to fix it is to update the record with the ID=1 to '--':
update yourTable set Value = '--' where id = 1
Then you will be required to re-insert the first record into the table:
INSERT INTO yourTable (Value)
VALUES('the value that was originally inserted as 1')
However, if the order of the already inserted records is important then you can insert the '--' value as the ID = 0. In this case you need to disable the IDENTITY column using the SET IDENTITY_INSERT:
SET IDENTITY_INSERT yourTable ON
INSERT INTO yourTable (ID, Value)
VALUES(0, '--')
SET IDENTITY_INSERT yourTable OFF
This way the order of inserted records will be preserved and the '--' will be inserted with the ID of 0
BTW, for mySQL you can insert into the IDENTITY column by default

Because Your ID column auto increment (IDENTITY), when you insert, you mustn't insert ID column. To insert your table, you just insert other columns.
Code insert like this:
INSERT INTO Your_Table (ColA, ColB, ...) -- `except identity colums`
VALUES (A, B, ...)
INSERT INTO Your_Table
VALUES (A, B, ...) -- except identity colums
INSERT INTO Your_Table
SELECT ColA, ColB, ... FROM Other_Table -- except identity colums
If Your_Table empty:
INSERT INTO Your_Table (Value)
VALUES ('--')
INSERT INTO Your_Table
SELECT '--'
If not:
UPDATE Your_Table
SET Value = '--'
WHERE ID = 1
------------------------ More Infor -------------------------------------------
If you want to first row have ID = 1. You can set ID column have IDENTITY(1,1). Like this:
CREATE TABLE Your_Table
(
ID INT IDENTITY(1, 1) PRIMARY KEY,
Value VARCHAR(50) NULL
)
Or, After you create Your_Table, you can set right-click Your_Table, select Design, select ID column. Look Column Properties below, expand Identity Specification, Double click (Is identity), then set value Identity Increment and Identity Seed

Related

Insert single column return value into multiple columns of another table

I have a db setup like below
create table children_A (
id serial primary key,
value text not null
);
create table children_B (
id serial primary key,
value text not null
);
create table parent_C (
id serial primary key,
child_A_id int not null,
child_B_id int not null
);
and I have an insert query like
with
children_A_insert as ( -- upsert in children_A and return id
insert into children_A(value)
values ('John')
on conflict (value)
do nothing
returning id
),
children_B_insert as ( -- upsert in children_B and return id
insert into children_B(value)
values ('Terry')
on conflict (value)
do nothing
returning id
)
-- insert into parentC(child_A_id, child_B_id) how to write this insert and select query ??
select children.id as id -- how can I trasnlate returning array of intergers into different columns for parent_C table
from (
select id from children_A_insert -- either get newly inserted id
union all
select id from children_A where value = 'John' -- or get the existing id from the children table
union all
select id from children_B_insert
union all
select id from children_B where value = 'Terry'
)
which essentially a query to insert into multiple tables in a single sql command.
result of the query is something like
id
---------
10
12
the problem is I want to take children.id as id and insert the returning ids into the parent table like
id
---------
10
12
should get trasnlated to
child_A_id | child_B_id
10 | 12
in the parent table. Unfortunately, id being a single column can not insert values in parent_C's multiple columns.
Is there a way to use children.id (single column) and insert the values to parent_C's multiple columns.
First of all you must add some constraint in children_A table and children_B table for upsert. Now to achieve the above insert you can try like below:
with
children_A_insert as (
insert into children_A(value)
values ('John')
on conflict (value)
do
update set value=EXCLUDED.value
returning id
),
children_B_insert as (
insert into children_B(value)
values ('Terry')
on conflict (value)
do
update set value=EXCLUDED.value
returning id
)
insert into parent_c (child_A_id,child_B_id)
values((select id from children_A_insert),
(select id from children_B_insert))
DEMO
NOTE: Above will work if you are inserting only one value in each table at a time

Generate ID for duplicate values in sql server

I found following link to assign identical ID to duplicates in SQL server,
my understanding there is no sql server function to automatically generate it rather than using insert and update queries in link attached, is that statement True, if yes, then what would be the trigger if for example someone insert data to MyTable then run insert and update query from link:
Assign identical ID to duplicates in SQL server
INSERT INTO secondTable (word) SELECT distinct word FROM MyTable;
UPDATE MyTable SET ID = (SELECT id from secondTable where MyTable.word = secondTable.word)
thanks,
S
Is this what you want? I can't think of an "automatic" solution that would just increase the Id for new words.
CREATE TABLE MyTable (
Id INT NOT NULL,
Word NVARCHAR(255) NOT NULL
PRIMARY KEY (Id, Word)); -- primary key will make it impossible to have more than one combination of word and id
DECLARE #word NVARCHAR(255) = 'Hello!';
-- Get existing id or calculate a new id
DECLARE #Id INT = (SELECT Id FROM MyTable WHERE Word = #word);
IF(#id IS NULL) SET #Id = (SELECT MAX(Id) + 1 FROM MyTable);
INSERT INTO MyTable (Id, Word)
VALUES (#id, #word)
SELECT * FROM MyTable
If you can't for some reason have id and word as a combined primary key, you may use an unique index to make sure that there is only one combination

Add a column ID with a unique value for each row

I have an existing table with existing data and I want to add new column (named ID) with auto-increment and I want to add a unique value for each row.
Is there an other way than fetching all data and do an update for each row to set this value ?
If you need it in a SELECT:
SELECT *, ROW_NUMBER() OVER(ORDER BY ...A ORDER VALUE) as id
FROM yourTable
If you need it in your table:
ALTER TABLE yourTable ADD id int identity(1,1)
Here is a demo for the output of the ALTER TABLE:
CREATE TABLE #temp(name nvarchar(50))
INSERT INTO #temp(name) VALUES(N'Kai'),(N'Bernd'),(N'Flo'),(N'Pete')
SELECT * FROM #temp
-- This is what you need to do
ALTER TABLE #temp
ADD id int identity(1,1) -- This will add and fill the new column
SELECT * FROM #temp
DROP TABLE #temp

Extract Row ID from Table - Insert Then Select

Is it Possible to extract the ID of the record being inserted in a table at the time of inserting dat particular record into that table ??? Reference to Sql Server
Read about INSERT with OUTPUT. This is in my experience the easiest way of achieving an atomic INSERT outputting an inserted value.
Example, assuming that Table contains an auto-incremented field named ID:
DECLARE #outputResult TABLE (ID BIGINT)
INSERT INTO Table
(
Field1,
Field2
)
OUPUT INSERTED.ID INTO #outputResult
VALUES
(
....
)
SELECT TOP 1 ID FROM #outputResult
You can select the ID afterwards with
SELECT ##IDENTITY
or
SELECT SCOPE_IDENTITY()

How to insert sequential numbers in primary key using select subquery?

I am reading a table A and inserting the date in Table B (both tables are of same structure except primary key data type). In Table B, Primary key is int whereas in Table A it is UniqueIdentifier.
INSERT INTO TableB
(ID, Names, Address)
(select ID, Names, Address from TableA)
Now how can i insert int type incremental value (1,2,3,so on) in TableB instead of uniqueidentifier from TableA using above script.
Help?
Why not change Table B so that the primary key is an identity which auto-increments?
Go to the table properties, select the ID field, under "Identity specification", set "Identity Increment" = 1, "Identity Seed" = 1. By doing that, the ID becomes auto incremental...
Then your insert statement would be something like:
INSERT INTO TableB (Names, Address) (select Names, Address from TableA)
If changing the schema of your TableB is not an option then add a rank to your select statement like this:
insert into tableB select rank() over(order by id), name, address from tableA
This will always start at 1. I you could add + 10 if you wanted to start your numbering at a number other than 1. I'm sure you get the idea from there.
CREATE TABLE TableB
(
ID int PRIMARY KEY IDENTITY(1,1),
Name nvarchar(200),
Address nvarchar(200)
)
Then, in the query, don't specify the value of the identity column.
INSERT INTO TableB(Name, Address)
SELECT Name, Address FROM TableA