How to insert into a table with just one IDENTITY column? - sql

(Came up with this question in the course of trying to answer this other one)
Consider the following MS-SQL table, called GroupTable:
GroupID
-------
1
2
3
where GroupID is the primary key and is an Identity column.
How do you insert a new row into the table (and hence generate a new ID) without using IDENTITY_INSERT ON?
Note that this:
INSERT INTO GroupTable() Values ()
... won't work.
edit: we're talking SQL 2005 or SQL 2008 here.

This should work:
INSERT INTO GroupTable DEFAULT VALUES

Here you go:
INSERT INTO GroupTable DEFAULT VALUES

It is possible to insert more than one row at a time.
For e.g., to insert 30 rows.
INSERT INTO GroupTable DEFAULT VALUES
GO 30
This will insert 30 rows by incrementing the identity column each time.

Can you try using a Sequence or something similar? Where you select from a Sequence and it will give you the next value in the sequence.

This will work actually--
insert into TABLE default values

Related

How to insert row in sql sever table if table contains only two columns one is identity and other one is default constraint [duplicate]

(Came up with this question in the course of trying to answer this other one)
Consider the following MS-SQL table, called GroupTable:
GroupID
-------
1
2
3
where GroupID is the primary key and is an Identity column.
How do you insert a new row into the table (and hence generate a new ID) without using IDENTITY_INSERT ON?
Note that this:
INSERT INTO GroupTable() Values ()
... won't work.
edit: we're talking SQL 2005 or SQL 2008 here.
This should work:
INSERT INTO GroupTable DEFAULT VALUES
Here you go:
INSERT INTO GroupTable DEFAULT VALUES
It is possible to insert more than one row at a time.
For e.g., to insert 30 rows.
INSERT INTO GroupTable DEFAULT VALUES
GO 30
This will insert 30 rows by incrementing the identity column each time.
Can you try using a Sequence or something similar? Where you select from a Sequence and it will give you the next value in the sequence.
This will work actually--
insert into TABLE default values

Creating New GUID automatically while inserting a new row to an existing table Not Working

I have an existing table in MS SQL called myTab.
It has the following fields
empno(PK) nchar(10),
age int
Now, i want to add a myGUID column and fill it up with a GUID whenever i insert a new row as well as Updating existing rows.
So i added the statement
ALTER TABLE myTab ADD myGUID uniqueidentifier DEFAULT NewId() NOT NULL;
Updating existing rows works correctly.
But, when i try to insert values,
INSERT INTO myTab VALUES ( 1000, 22 );
It fails, and gives the following message
**Column name or number of supplied values does not match table definition.**
When i do
insert into sourav_test2 values (20055711,23,NEWID());
The above statement works.
I want a GUID to be filled without changing the insert statement. Is it possible via a Trigger or a Function?
Always list the columns you are inserting!
INSERT INTO myTab (empno, age)
VALUES ('1000', 22);
Also use correct types for the values. Unmentioned columns will be assigned their default values, or NULL if there is no explicit default.
Your table has three columns, so if you leave out the column list, then the insert expects three values. You can still set a default, if you want by using the DEFAULT keyword in the VALUES clause:
INSERT INTO myTab (empno, age, myGUID)
VALUES ('1000', 22, DEFAULT);
Sourav's question about triggers got me thinking, so I tried a little test. Why?
Imagine a scenario where an application has already been written with thousands of INSERT statements that leave off the column list. In this case, if you could write an INSTEAD OF INSERT trigger that provides the column list, you could hopefully save yourself from correcting thousands of INSERT statements due to a newly added column.
Off the top of my head, I admittedly did not know if this could work.
So I wrote this little test:
CREATE TABLE tt (ColA varchar(1));
INSERT INTO tt VALUES ('a');
ALTER TABLE tt
ADD ColB uniqueidentifier DEFAULT NEWID();
GO
CREATE TRIGGER tr_tt
ON tt
INSTEAD OF INSERT
AS
INSERT INTO tt (ColA)
SELECT ColA FROM inserted;
GO
INSERT INTO tt VALUES ('a');
SELECT * FROM tt;
DROP TABLE tt;
I also tried a variation of the TRIGGER with the following INSERT just to be thorough:
INSERT INTO tt (ColA, ColB)
SELECT ColA, NEWID() FROM inserted;
The result was the same in both cases: The same error as reported in the question. So to answer the question:
Can't we use a trigger here which can do it?
The answer is NO. Even if you put an INSTEAD OF INSERT TRIGGER on the table, the parser will still not let you write an INSERT..VALUES() statement unless the number and order of VALUES exactly matches the definition of the table. A TRIGGER cannot be used to get around it.
Sooner or later, lazy coding exacts its price.

Multiple row insert into two tables avoiding loops

I have a set of value which have to be inserted into two tables.Input has say 5 row and I have to insert these 5 rows into table A first.Table A has a identity column.Next i have to insert these 5 rows into table B with an extra column which is the identity from table A.
How this can be done with out using any loops?
Any help will be highly helpful.
INSERT INTO TABLE_A(COL2,COL3)
SELECT COL2,COL3 FROM #TEMP_TAB
set #identityval=##identity
INSERT INTO TABLE_B(COLA,COLB,COLC)
SELECT #identityval,COL2,COL3,COL4 FROM #TEMP_TAB
You cannot insert into multiple tables using a single statment.
What you could do is create an insert trigger on Table A so that after the insert occurs this performs the new insert with the identity of the value inserted into Table A and insert it into Table B.
Here is one solution.
take max of identity column from table TABLE_A
insert new records in table TABLE_A
then insert records on TABLE_B from TABLE_A with Identity greater than last max identity.
Thanks,
Gopal
What you want to do is not possible.
You can get only the value from the last insert using the ##identity variable. This way its possible to add to multiple tables setting the right foreign key without selecting the just inserted row again using a cursor. This approach is not useful when inserting multiple rows at once.
From the documentation:
Use the ##identity global variable to retrieve the last value inserted into an IDENTITY column. The value of ##identity changes each time an insert or select into attempts to insert a row into a table.
Here is a procedure which inserts a single row and you can use the return value to create a reference to the inserted data in another table:
create procedure reset_id as
set identity_insert sales_daily on
insert into sales_daily (syb_identity, stor_id)
values (102, "1349")
select ##identity
select ##identity
execute reset_id

Adding auto-incremented values to a table with one column

I need to create a table that basically keeps a list of indices only. Therefore I've created a table with just one, auto-incremented column called 'id'. However, I can't seem to implicitly add auto-incremented values to this table.
I know that usually when you have such a column in a table (with more than just this column) you can do:
INSERT INTO TABLE (col1, col2 ...) VALUES (val1, val2 ...)
And if you don't specify the auto-incremented column, it would automatically get a value. However, things like:
INSERT INTO TABLE () VALUES ()
INSERT INTO TABLE
INSERT INTO TABLE ()
etc. all produce an error on my single-columned table. Can anyone offer a solution?
Thanks.
p.s. I'm using Sqlite, in case it matters.
Try this
INSERT INTO dbo.Table DEFAULT VALUES
See this answer:
Previous answer
Try the following:
INSERT INTO YOUR_TABLE(YOUR_ID) VALUES (NULL);

how to compare the values inside a table in sql

how to
compare the values of same table(say for eg: Order table) each and every time the record get inserted ,
if the record with same values get inserted already in same table i should not insert the new record with same values. how to do that exactly in sql server 2008
If exists(select * from Order where key_column=#some_value)
print 'data already exists'
else
Insert into Order(columns) values (#some_value,...)
I'd suggest adding a unique index on the key columns...
ALTER TABLE mytable ADD UNIQUE INDEX myindex (keycolumn1, keycolumn2, ...);
That'd make it impossible to insert a duplicate by accident.