Insert rows based on insert statement (nested insert) - sql

A common insert statement is this..
INSERT INTO tbl_name (ID) VALUES (1)
What I wanted to achieve is to Insert an ID using another insert statement from another table.. It would look like this
INSERT INTO tbl_name VALUES (INSERT INTO tbl_name2 (ID) VALUES (1))
I have tried it but it's giving me errors..
INSERT INTO tblReport_OPA (ID_Main) VALUES (INSERT INTO tblReport_OPF (ID_Main) VALUES (1))
I'm currently developing under vb.net 2010 and sql express 2005

You probably can use OUTPUT clause, like this:
INSERT INTO tblReport_OPF (ID_Main)
OUTPUT Inserted.Id_Main
INTO tblReport_OPA
SELECT 1 as Id_Main
Note you'll have to use SELECT instead of VALUES

Opyionally a merge can be used.
merge into #a T1
using (select -1 as ID)Q on Q.ID=T1.ID
WHEN NOT matched by target then
insert(id) values(1)
output
inserted.id
INTO #b;

Related

How to insert values into a postgres table using for loop?

I have a script like this in postgres
begin;
INSERT INTO "schema"."table"(price, different_table_foreign_key)
VALUES
(1, 1)
end;
for testing purposes I want to fill table 100 times with the same values as seen above.
how can I do this using a for loop?
No need for a loop, you can use generate_series() for that:
INSERT INTO "schema"."table"(price, different_table_foreign_key)
select 1,1
from generate_series(1,100);
If you want a different value for each row, just use the one returned by `generate_series()
INSERT INTO "schema"."table"(price, different_table_foreign_key)
select 1, g.value
from generate_series(1,100) as g(value)

How to to get the value of an auto increment column in postgres from a .sql script file?

In postgres I have two tables like so
CREATE TABLE foo (
pkey SERIAL PRIMARY KEY,
name TEXT
);
CREATE TABLE bar (
pkey SERIAL PRIMARY KEY,
foo_fk INTEGER REFERENCES foo(pkey) NOT NULL,
other TEXT
);
What I want to do is to write a .sql script file that does the following
INSERT INTO foo(name) VALUES ('A') RETURNING pkey AS abc;
INSERT INTO bar(foo_fk,other) VALUES
(abc, 'other1'),
(abc, 'other2'),
(abc, 'other3');
which produces the error below in pgAdmin
Query result with 1 row discarded.
ERROR: column "abc" does not exist
LINE 3: (abc, 'other1'),
********** Error **********
ERROR: column "abc" does not exist
SQL state: 42703
Character: 122
Outside of a stored procedure how do a define a variable that I can use between statements? Is there some other syntax for being able to insert into bar with the pkey returned from the insert to foo.
You can combine the queries into one. Something like:
with foo_ins as (INSERT INTO foo(name)
VALUES ('A')
RETURNING pkey AS foo_id)
INSERT INTO bar(foo_fk,other)
SELECT foo_id, 'other1' FROM foo_ins
UNION ALL
SELECT foo_id, 'other2' FROM foo_ins
UNION ALL
SELECT foo_id, 'other3' FROM foo_ins;
Other option - use an anonymous PL/pgSQL block like:
DO $$
DECLARE foo_id INTEGER;
BEGIN
INSERT INTO foo(name)
VALUES ('A')
RETURNING pkey INTO foo_id;
INSERT INTO bar(foo_fk,other)
VALUES (foo_id, 'other1'),
(foo_id, 'other2'),
(foo_id, 'other3');
END$$;
You can use lastval() to ...
Return the value most recently returned by nextval in the current session.
This way you do not need to know the name of the seqence used.
INSERT INTO foo(name) VALUES ('A');
INSERT INTO bar(foo_fk,other) VALUES
(lastval(), 'other1')
, (lastval(), 'other2')
, (lastval(), 'other3')
;
This is safe because you control what you called last in your own session.
If you use a writable CTE as proposed by #Ihor, you can still use a short VALUES expression in the 2nd INSERT. Combine it with a CROSS JOIN (or append the CTE name after a comma (, ins) - same thing):
WITH ins AS (
INSERT INTO foo(name)
VALUES ('A')
RETURNING pkey
)
INSERT INTO bar(foo_fk, other)
SELECT ins.pkey, o.other
FROM (
VALUES
('other1'::text)
, ('other2')
, ('other3')
) o(other)
CROSS JOIN ins;
Another option is to use currval
INSERT INTO foo
(name)
VALUES
('A') ;
INSERT INTO bar
(foo_fk,other)
VALUES
(currval('foo_pkey_seq'), 'other1'),
(currval('foo_pkey_seq'), 'other2'),
(currval('foo_pkey_seq'), 'other3');
The automatically created sequence for serial columns is always named <table>_<column>_seq
Edit:
A more "robust" alternative is to use pg_get_serial_sequence as Igor pointed out.
INSERT INTO bar
(foo_fk,other)
VALUES
(currval(pg_get_serial_sequence('public.foo', 'pkey')), 'other1'),
(currval(pg_get_serial_sequence('public.foo', 'pkey')), 'other2'),
(currval(pg_get_serial_sequence('public.foo', 'pkey')), 'other3');

Not in In SQL statement?

I have set of ids in excel around 5000 and in the table I have ids around 30000. If I use 'In' condition in SQL statment I am getting around 4300 ids from what ever I have ids in Excel. But If I use 'Not In' with Excel id. I have getting around 25000+ records. I just to find out I am missing with Excel ids in the table.
How to write sql for this?
Example:
Excel Ids are
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
Table has IDs
1,
2,
3,
4,
6,
8,
9,
11,
12,
14,
15
Now I want get 5,7,10 values from Excel which missing the table?
Update:
What I am doing is
SELECT [GLID]
FROM [tbl_Detail]
where datasource = 'China' and ap_ID not in (5206896,
5206897,
5206898,
5206899,
5117083,
5143565,
5173361,
5179096,
5179097,
5179150)
Try this:
SELECT tableExcel.ID
FROM tableExcel
WHERE tableExcel.ID NOT IN(SELECT anotherTable.ID FROM anotherTable)
Here's an SQL Fiddle to try this: sqlfiddle.com/#!6/31af5/14
You're probably looking for EXCEPT:
SELECT Value
FROM #Excel
EXCEPT
SELECT Value
FROM #Table;
Edit:
Except will
treat NULL differently(NULL values are matching)
apply DISTINCT
unlike NOT IN
Here's your sample data:
declare #Excel Table(Value int);
INSERT INTO #Excel VALUES(1);
INSERT INTO #Excel VALUES(2);
INSERT INTO #Excel VALUES(3);
INSERT INTO #Excel VALUES(4);
INSERT INTO #Excel VALUES(5);
INSERT INTO #Excel VALUES(6);
INSERT INTO #Excel VALUES(7);
INSERT INTO #Excel VALUES(8);
INSERT INTO #Excel VALUES(9);
INSERT INTO #Excel VALUES(10);
declare #Table Table(Value int);
INSERT INTO #Table VALUES(1);
INSERT INTO #Table VALUES(2);
INSERT INTO #Table VALUES(3);
INSERT INTO #Table VALUES(4);
INSERT INTO #Table VALUES(6);
INSERT INTO #Table VALUES(8);
INSERT INTO #Table VALUES(9);
INSERT INTO #Table VALUES(11);
INSERT INTO #Table VALUES(12);
INSERT INTO #Table VALUES(14);
INSERT INTO #Table VALUES(15);
Import your excel file into SQL Server using the Import Data Wizard found in SQL Server Management Studio.
Then you can write the following query to find any IDs which are in the file but not in the table:
SELECT id
FROM imported_table
WHERE id NOT IN (SELECT id FROM db_table)
You should move excel data to a table in SQL Server, and then do the query in SQL Server.
select distinct id from Excel where id not in (select your ids from Sqltable)
(Obviously select your ids from Sqltable is a select which returns the Ids existing on SQL Server).
You may think that moving data to SQL Server is hard to do, but, on the contrary, it's very easy:
1) create a table
CREATE TABLE ExcelIds (Id int)
2) add a new column in excel with the following formula:
="insert into ExcelIds values(" & XX & ")"
where XX is the reference to the cell in the column with excel Ids.
3) copy the "inserts" from Excel into SSMS or whatever tool you're usin in SQL Server, and execute them.
Now you have 2 tables in SQL Server, so that querying it is absolutely easy.
When you're over, just drop the table
DROP TABLE ExcelIds
NOTE: I didn't create a key on SQL Server table because I suppose that the Ids can be repeated. Neither is justified to create a more complex SQL Query to avoid duplicates in ExcelIds for this ad hoc solution.

Is there any way to retrieve inserted rows of a command

We probably all know SCOPE_IDENTITY() to retrieve the identity generated by a single insert. Currently I'm in the need of some kind of magic variable or function to retrieve all the rows generated by a statement, eg:
INSERT INTO [dbo].[myMagicTable]
(
[name]
)
SELECT [name]
FROM [dbo].[myMagicSource]
WHERE /* some weird where-clauses with several subselects ... */;
INSERT INTO [dbo].[myMagicBackupTable]
(
[id],
[name]
)
SELECT
[id],
[name]
FROM ???
An insert trigger is no option, as this will perform a single insert which is a problem for a batch of 10.000 rows...
So, is there any way to achieve this?
We are using mssql2005<
For SQL Server 2005+, you can use the OUTPUT clause.
DECLARE #InsertedIDs table(ID int);
INSERT INTO [dbo].[myMagicTable]
OUTPUT INSERTED.ID
INTO #InsertedIDs
SELECT ...
You could define a temporary table (possibly a table variable) and make use of the OUTPUT clause on your INSERT (you can make use of the Inserted pseudo-table, like in a trigger):
DECLARE #NewIDs TABLE (MagicID INT, Name VARCHAR(50))
INSERT INTO [dbo].[myMagicTable]([name])
OUTPUT Inserted.MagicID, Inserted.Name INTO #NewIDs(MagicID, Name)
SELECT [name]
FROM [dbo].[myMagicSource]
WHERE /
and then use that table variable after the INSERT:
INSERT INTO
[dbo].[myMagicBackupTable]([id], [name])
SELECT MagicID, [name]
FROM #NewIDs
and go from there.

SQL Command to execute multiple times?

I have situations that I need to write multiple rows of the same value to setup some tables. Say I have to add 120 rows with two columns populated. I am looking for a shortcut, instead of having the Insert line repeated n times. How to do this?
In SQL Server Management Studio, you can use the "GO" keyword with a parameter:
INSERT INTO YourTable(col1, col2, ...., colN)
VALUES(1, 'test', ....., 25)
GO 120
But that works only in Mgmt Studio (it's not a proper T-SQL command - it's a Mgmt Studio command word).
Marc
How about
Insert Table( colsnames )
Select Top 120 #value1, #Value2, etc.
From AnyTableWithMoreThan120Rows
Just make sure the types of the values in the #Value list matches the colNames List
what about
insert into tbl1
(col1,col2)
(select top 120 #value1,#value2 from tbl2)
if in sql server 2008 . new in sql server 2008 to insert into a table multiple rows in a single query .
insert into tbl1
(col1,col2)
values
(#value1,#value2),(#value1,#value2),.....(#value1,#value2)
Put the values in an unused table for safe keeping. From there you can insert from this table to the tables you need to setup.
Create an Excel Spreadsheet with your data.
Import the speadsheet into Sql Server.
You can even try with something like this(just an example)
declare #tbl table(col1 varchar(20),col2 varchar(20))
; with generateRows_cte as
(
select
1 as MyRows
union all
select
MyRows+1
from generateRows_cte
where MyRows < 120
)
insert into #tbl(col1,col2)
select
'col1' + CAST(MyRows as varchar),'col2' + CAST(MyRows as varchar)
from generateRows_cte OPTION (MAXRECURSION 0)
select * from #tbl
Note:- Why not you are trying with Bulk insert into SqlServer from a dataset ? I didnot notice first that u have a front end too(VB)!