Single SQLstatement for many INSERTs - sql

Please see the DDL below:
CREATE TABLE #Test (ID INT NOT NULL IDENTITY, Name varchar(100), [Key] int, primary key (ID))
INSERT INTO #Test (Name, [Key]) values ('Ian',1)
INSERT INTO #Test (Name, [Key]) values ('Iain',1)
INSERT INTO #Test (Name, [Key]) values ('Eon',1)
INSERT INTO #Test (Name, [Key]) values ('Mark',2)
INSERT INTO #Test (Name, [Key]) values ('Steven',2)
and the DDL below:
CREATE TABLE #Test2 (ID INT NOT NULL IDENTITY, Name varchar(100), primary key (ID))
INSERT INTO #Test2 (Name) values ('Graham')
INSERT INTO #Test2 (Name) values ('William')
INSERT INTO #Test2 (Name) values ('Neil')
INSERT INTO #Test2 (Name) values ('Calum')
INSERT INTO #Test2 (Name) values ('Wayne')
I want to INSERT everything from #Test2 into #Test. I want each record in #Test2 to have a unique Key in #Test. In affect I want this to happen:
INSERT INTO #Test (Name, [Key]) VALUES ('Graham', 3)
INSERT INTO #Test (Name, [Key]) VALUES ('William', 4)
INSERT INTO #Test (Name, [Key]) VALUES ('Calum', 5)
INSERT INTO #Test (Name, [Key]) VALUES ('Wayne', 6)
There are millions of records in #Test and #Test2.
Is it possible to do all the INSERTS with a single SQL statement or do I have to use a cursor.

You need just new numbers that are higher than the max. key that exists? This should work:
declare #maxkey int
select #maxkey = max([Key]) from Test
insert into Test (Name, [Key])
select Name, row_number () over (order by (select null)) + #maxkey
from Test2
This just fetches the max. key and uses row_number to add numbers to the rows coming from Test2.
SQL Fiddle

You can try some logic like this:
insert into #Test
select Name, ((select max([Key]) from #Test) + ID) as [Key]
from #Test2
order by ID asc;
Here is my Fiddle example: Fiddle

Related

Here is a Sql-Server query, How do it in Postgresql?

Here is a SQL-Server query, How do it in PostgreSQL?
DECLARE #p_key as int= NEXT VALUE FOR ProductSequence;
INSERT INTO Product(ID,Name,Price) VALUES(#p_key,#Name,#Price);
INSERT INTO ProductInfo(ID,Guid,DateCreation, DateLastChange, AgentCreationID,AgentLastChangeID) VALUES(#p_key, #Guid, #DateCreation, #DateLastChange, #AgentCreationID, #AgentLastChangeID);
SELECT #p_key;
Assuming product.id is defined as identity you can do that with a writeable CTE:
with new_product as (
insert into product (name, price)
values (...)
returning id
)
insert into product_info (id, guid, date_creation, date_last_change, anget_creation_id, agent_last_change_id )
select id, 'guid', ...
from new_product;
Otherwise just use nextval() and lastval()
insert into product
(id, name, price)
values
(nextvalue('product_id_seq'), ...);
insert into product_info
(id, guid, date_creation, date_last_change, anget_creation_id, agent_last_change_id )
values
(lastval(), ....);

How to insert keyvalue as a row in table?

I have table variable which contains records in terms of key,value pair of a table. where key is the column of table and value is the value for that column
below is table variable
DECLARE #Table TABLE(
FieldName varchar(100),
FieldValue varchar(max))
insert into #Table values('Title','NewFrom')
insert into #Table values('Points','4')
insert into #Table values('createdby','5')
I have above values in UsersInformation.This is physical table of sql server
has following column.
UserID int autoincrement(identity)
Title nvarchar(100),
Points int,
createdby int
I want that all values of #Table should be as a single row of UserInformation table.
How can be using sql server?
Have not tested but this should work
INSERT INTO UsersInformation (Title, Points, createdby)
SELECT Title, Points, createdby FROM (SELECT FieldName, FieldValue
FROM #Table) AS SourceTable
PIVOT (MAX(FieldValue) FOR FieldName IN ([Points], [Title], [createdby])) AS PivotTable;
Based on your comment you will need to add a key to your source #table
DECLARE #Table TABLE(
id int,
FieldName varchar(100),
FieldValue varchar(max))
insert into #Table values(1,'Title','NewFrom')
insert into #Table values(1,'Points','4')
insert into #Table values(1,'createdby','5')
insert into #Table values(2,'Title','NewFrom2')
insert into #Table values(2,'Points','44')
insert into #Table values(2,'createdby','55')
insert into #Table values(3,'Title','NewFrom3')
insert into #Table values(3,'Points','444')
Then you can run the query:
SELECT [Title], [Points], [createdby]
FROM #Table
PIVOT
(
max(FieldValue) FOR [FieldName] IN ([Title], [Points], [createdby])
) AS P

insert data to temporary table in sql 2008

CREATE TABLE #tmpt
(
ID INT
,sName varchar(20)
)
INSERT INTO #tmpt VALUES (1,'ran')
INSERT INTO #tmpt VALUES (2,'pan')
INSERT INTO #tmpt VALUES (3,'fan')
INSERT INTO #tmpt VALUES (4,'gan')
This type of insert does not work. Can you help

MS SQL Server Last Inserted ID

In my database all tables are using a common table for Sequence(ID_Table).
TABLE_ID has two fields (Common_ID, Table_Name).
If I insert any record in the table, I have to first insert a record in Table_ID(Auto-increment, Table_name) then use that Auto-increment value in my Other Table.
For example, I want to insert in Table_Products which has fields ID(Common_ID), Product_Name, Product_ID(Auto Increment)
I want to do something like this:
INSERT INTO TABLE_ID (Table_NAME), Values (Table_Products)
Get the Inserted ID and use it in Table_Products:
INSERT INTO Table_Products (ID, Product_Name, Product_ID(Auto Increment)
VALUES (ID from TABLE_ID, SomeProduct, Increment)
Try this one -
DECLARE #ID BIGINT
INSERT INTO dbo.TABLE_ID (Table_NAME)
SELECT 'Table_Products'
SELECT #ID = SCOPE_IDENTITY()
INSERT INTO dbo.Table_Products (ID, Product_Name)
SELECT #ID, 'SomeProduct'
You can use an insert statement with the output clause to generate a new Common_ID. Using insert ... select, you can specify that ID in an insert operation:
declare #Common_ID as table(ID int)
insert Table_ID
(Table_Name)
output inserted.Common_ID into #Common_ID
values ('Table_Products')
insert Table_Products
(ID, Product_Name)
select ID
, 'Some Product'
from #Common_ID
Use SCOPE_IDENTITY() after ur insert statementto get the last inserted id.
DECLARE #Product_Id int
INSERT INTO TABLE_ID (Table_NAME) VALUES (Table_Products);
SELECT #Product_Id=SCOPE_IDENTITY();
Insert INTO Table_Products (ID, Product_Name)
VALUES (ID from TABLE_ID, 'SomeProduct')
Dear friend you have to select id of last record inserted
and then pass it in another table so bellow code will help you very well
Insert INTO TABLE_ID (Table_NAME), Values (Table_Products)
DECLARE #ID int;
set #ID = SCOPE_IDENTITY();
Insert INTO Table_Products (ID, Product_Name)
Values (#ID, SomeProduct)
this code will solve your problem i define #ID for your last record id and then insert it in your other table
For MySql use select LAST_INSERT_ID();
All the other answers so far declare intermediary variables for SCOPE_IDENTITY(), but it could be simpler:
INSERT INTO dbo.TABLE_ID (Table_NAME) VALUES 'Table_Products';
INSERT INTO dbo.Table_Products (ID, Product_Name) VALUES (SCOPE_IDENTITY(),'SomeProduct');
You could be also more table-specific using IDENT_CURRENT()
Insert INTO TABLE_ID (Table_NAME), Values (Table_Products)
select #NewID=IDENT_CURRENT('TABLE_ID')
Insert INTO Table_Products (ID, Product_Name, Product_ID
Values (#NewID, SomeProduct, Increment)

referencing a table variable

I have a problem referencing a table variable in a update statement. Seems I can't use the #a.id column (the compiler says it's not declared).
The following example was written only to illustrate the problem, meaning that I know that I can solve the problem in the current example renaming the column id and avoiding the #a.id reference, but it's not a option, I really can't do that. I saw some solutions using the from statement to alias the table being updated, but in this example I'm using the from statement for something else. Is there another way to solve it?
declare #a table
(
id int not null,
name varchar(100) null
)
insert into #a (id, name) values (1, null)
insert into #a (id, name) values (2, null)
insert into #a (id, name) values (3, null)
declare #b table
(
id int not null,
name varchar(100) null
)
insert into #b (id, name) values (1, 'one')
insert into #b (id, name) values (2, 'two')
update #a
set
name = f.name
from
(
select
id,
name
from #b
where
id = #a.id
) f
where
#a.id = f.id
Try something like this:
declare #a table
(
id int not null,
name varchar(100) null
)
insert into #a (id, name) values (1, null)
insert into #a (id, name) values (2, null)
insert into #a (id, name) values (3, null)
declare #b table
(
id int not null,
name varchar(100) null
)
insert into #b (id, name) values (1, 'one')
insert into #b (id, name) values (2, 'two')
update upd
set
name = [#b].name
from #a AS upd
INNER JOIN #b
ON upd.id = [#b].id
And BTW following will work too:
update #a
set
name = f.name
from
(
select
id,
name
from #b
) f
where
[#a].id = f.id
The reference to #a.id is illegal because the table is out of scope at that point. Here's what you might try:
Update #a
set name = f.name
from #b g
join #a f
on g.id=f.id