Increment number on insert into? - sql

Here's my dilemma,
I have the following columns:
ID_C int and NAME varchar
Problem is that ID_C is not set to auto-increment because it's linked to another table with the information on that particular ID_C number. So it cannot auto-increment without having the number in there first, that's why it's not set for auto-increment.
How can I do
INSERT INTO Table (ID_C, name)
VALUES (<<This place should query for the last item and increment on the result>>,'Tom B. Erichsen')

INSERT INTO [Table](ID_C, name) SELECT MAX(ID_C)+1, 'stack' FROM user_table
you can use dml trigger also.(after insert)
refernce
http://www.mssqltips.com/sqlservertip/2342/understanding-sql-server-inserted-and-deleted-tables-for-dml-triggers/

Related

SQL insert ID from IDENTITY ID of the row being inserted

I would like to know, if there is a direct way to insert ID (generated at ID column with IDENTITY(1,1)) to another columns.
In another words, I am looking for SCOPE_IDENTITY() I could get at the time of inserting, not after the INSERT is commited.
I have a table, where there is a column with secondary ID (SID), which references rows from the same table and in some special cases it references itself.
The only way I know to do that is to do the INSERT and consequently UPDATE SID in those cases. Simplified example:
DECLARE #ID INT
INSERT INTO Table (SID) VALUES (NULL);
SELECT #ID = SCOPE_IDENTITY();
UPDATE Table SET SID = ID WHERE ID = #ID;
There are some glitches, i.e. due to the fact that the row may or may not reference itself, etc.
You can do this with an AFTER INSERT trigger. In case of self-reference, leave the column NULL and have the trigger set the column equal to the IDENTITY column.
In pseudo:
Join the table with inserted, filter where SID is NULL
For those rows, update the table and set SID = ID
If it is not possible to use the NULL value, in cases where it should be possible to have no reference at all, you can use another stub value. E.g. -1 if the IDs will always be positive. In that case, apply the above way of working and substitute NULL with -1.

SQL Server trigger can't insert

I beginning to learn how to write trigger with this basic database.
I'm also making my very 1st database.
Schema
Team:
TeamID int PK (TeamID int IDENTITY(0,1) CONSTRAINT TeamID_PK PRIMARY KEY)
TeamName nvarchar(100)
History:
HistoryID int PK (HistoryID int IDENTITY(0,1) CONSTRAINT HistoryID_PK PRIMARY KEY)
TeamID int FK REF Team(TeamID)
WinCount int
LoseCount int
My trigger: when a new team is inserted, it should insert a new history row with that team id
CREATE TRIGGER after_insert_Player
ON Team
FOR INSERT
AS
BEGIN
INSERT INTO History (TeamID, WinCount, LoseCount)
SELECT DISTINCT i.TeamID
FROM Inserted i
LEFT JOIN History h ON h.TeamID = i.TeamID
AND h.WinCount = 0 AND h.LoseCount = 0
END
Executed it returns
The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.
Please help thank. I'm using SQL Server
The error text is the best guide, it is so clear ..
You try inserting one value from i.TeamID into three columns (TeamID,WinCount,LoseCount)
consider these WinCount and LoseCount while inserting.
Note: I Think the structure of History table need to revisit, you should select WinCount and LoseCount as Expressions not as actual columns.
When you specify insert columns, you say which columns you will be filling. But in your case, right after insert you select only one column (team id).
You either have to modify the insert to contain only one column, or select, to retrieve 3 fields as in insert.
If you mention the columns where values have to be inserted(Using INSERT-SELECT).
The SELECT Statement has to contain the same number of columns that have been specified to be inserted. Also, ensure they are of the same data type.(You might face some issues otherwise)

Auto increment issues postgresql

Facing some issues with the auto-increment property in postgresql
I created a table say emp
create table emp
( empid serial,
empname varcha(50),
primary key (empid)
);
I inserted one value with empid as blank:
insert into emp (empname) values ('test1');
Next insert by specifying the empid value:
insert into emp (empid,empname) values (2,'test2');
Now, the next time if I insert a value without specifying the empid value, it will give an error because it will try to insert the empid as 2:
insert into emp (empname) values ('test3');
ERROR: duplicate key value violates unique constraint "emp_pkey"
DETAIL: Key (empid)=(2) already exists.
Can someone help me with a workaround for this issue so that with or without specifying a value, the autoincrement should pick up the max(value) +1 ??
Thanks
You can't cleanly mix use of sequences and fixed IDs. Inserting values without using the sequence won't update the sequence, so you'll get collisions.
If you're doing your manual insertions in a bulk load phase or something you can:
BEGIN
LOCK TABLE the_table IN ACCESS EXCLUSIVE MODE
Do your INSERTs
SELECT setval('seq_name', 14), replacing 14 with the new sequence value. This can be a subquery against the table.
COMMIT
... but in general, it's better to just avoid mixing sequence ID generation and manually assigned IDs.

Inserting a new column for serial number

I have table with 500 records in it and want to insert new column as "serial number" starting with 1.
If you care about the order in which the identity values are assigned, you are best off doing this:
CREATE TABLE dbo.NewTable
(
SerialNumber INT IDENTITY(1,1),
... other columns from original table ...
);
INSERT dbo.NewTable(...other columns...)
SELECT ...other columns...
FROM dbo.OriginalTable
ORDER BY ...ordering criteria...
OPTION (MAXDOP 1); -- to prevent parallelism from messing with identity
DROP TABLE dbo.OriginalTable;
EXEC sp_rename N'dbo.NewTable', N'OriginalTable', N'OBJECT';
You may have to deal with constraints etc. and you will want to do this in a transaction. The point is that just adding an identity column to the table with assign the identity values in an arbitrary order. If you don't care about how the existing values are assigned serial numbers, then just use Kyle's answer.
This could be achieved as follows:
alter table YourTable
add SrNo int identity(1,1)
in PostgreSQL just do:
ALTER TABLE ttaabbllee ADD COLUMN columnName serial NOT NULL; and done!..

Update value on insert into table in SQL Server

I am working with SQL Server - on inserting into a table, I have a unique constraint on a table column id. There is a possibility that when inserting, the value going into the id column is 0. This will cause an error.
Is it possible to update this id to another value during the insert if the id value is 0? This is to prevent the error and to give it a valid value.
Possibly a trigger?
A trigger is one way, but you may want to use a filtered index (CREATE UNIQUE INDEX, not as a table constraint) to ignore zero value. This way, you don't have to worry about what value to put there
Alternatively, if you want to populate it from another column, you can have a computed column with a unique constraint.
ALTER TABLE whatever
ADD ComputedUniqueCol = CASE WHEN Id = 0 THEN OtherCol ELSE Id END
If that's your primary key you can specify it as IDENTITY. Then it should generate a value for itself based on seed and increment (the default is seed=1 and default=1) so you don't have to worry about it.
CREATE TABLE MyTable
(
ID int PRIMARY KEY IDENTITY,
...
)
create an "instead of" trigger and check for the value on the ID.
CREATE trigger checkID
on YOUR_TABLE
instead of insert
as
begin
declare #id int
select #id=id from inserted
if (#id==0) begin
--DO YOUR LOGIC HERE AND THEN INSERT
end else begin
insert into DESTINATION_TABLE (VALUES)
SELECT VALUES FROM INSERTED
end
end