Use INSERT-OUTPUT to provide values for another INSERT - sql

Good day,
I was wondering if it is possible to use an INSERT-OUTPUT statement in such a way as to provide the value(s) for another, outer, INSERT statement. That way values can be added to an entity table and an intersection table in a single statement - I hope I'm wording this effectively. For example:
INSERT INTO [#tblIntersect] ([Entity1ID], [Entity2ID])
VALUES
(
INSERT INTO [#tblEntity1] ([Value])
OUTPUT [inserted].[ID] AS [entity1ID], #entity2ID AS [entity2ID]
VALUES ('One')
)
So the inner INSERT-OUTPUT statement will add a new entity to table #tblEntity1. The new entity's ID (which is set as IDENTITY(1, 1) will then be returned through the OUTPUT statement, along with a static value (which I already have in my code), to provide the two values for the outer INSERT statement.
The reason I think it might be possible is because execution of the inner INSERT-OUTPUT statement on its own returns a table anyway, and such output can usually be used to provide values for INSERT statements.
Obviously this example doesn't work; I was hoping it's just a simple syntax problem.
Thank you in advance for any comments and advice.

Your requirement is possible according to the documentation.
Assuming #tblIntersect has two matching id columns this should work
INSERT INTO [#tblEntity1] ([Value])
OUTPUT [inserted].[ID] AS [entity1ID], #entity2ID AS [entity2ID]
INTO #tblIntersect
VALUES ('One')

Related

INSERT statement for one column to populate each row

I have a table called books that I just altered to have a column called yearPUB. I'm trying to populate each row with a year but it's not working. This is the INSERT statement I'm using.
INSERT INTO books (yearPub)
VALUES (2002),
(2006),
(1999),
(2005),
(2003),
(2001),
(1998),
(1968),
(2009),
(1988),
Can someone tell me why it doesn't work?
You need to insert them one at a time, e.g.:
INSERT INTO books (yearPub) VALUES (2002);
INSERT INTO books (yearPub) VALUES (2006);
Alternatively, you could insert using a subquery with a select statement. The syntax may differ depending on what database you are using. For example, you could follow an example here and write something like:
INSERT INTO books (yearPub)
SELECT yearNumber FROM othertablename;

SQL Insert Query With Condition

I am trying to insert values into 1 column of a table when a condition is satisfied.
Note: The table already contains data for all the columns but for 1 which is empty. I would like to insert value into this 1 column depending on the WHERE clause.
I have this query:
INSERT INTO <TABLE_NAME>
(COLUMN_NAME)
(VALUE)
WHERE <CONDITION>
I am getting an exception:
Incorrect Syntax Near WHERE Keyword
I am able to do this using UPDATE:
UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>
But was wondering why the INSERT query was failing. Any advise appreciated.
As I understand your problem, you already have data in one row, and one column in that row does not have value, so you want to add value in to that column.
This the scenario for Update existing row, not the insert new row. You have to use UPDATE clause when data already present and you want to modify record(s). Choose insert when You want to insert new row in table.
So in your current scenario, Update Clause is your friend with Where Clause as you want to modify subset of records not all.
UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>
INSERT Clause does not have any Where Clause as per any RDBMS syntax(I think). Insert is condition less sql query, While SELECT, UPDATE, DELETE all are conditional commands, you can add Where Clause in all later ones.
In order to add a value into the one column when the rows are already populated, you will need to use the update statement.
If you need to insert a new row that has a where clause, you will need to use an insert into select statement:
INSERT INTO <table> (<columns>)
SELECT <columns>
FROM <table>
WHERE <condition>;
The SQL Insert dont accept where parameters, you could check this: SQL Insert Definition...
I do not know the whole question of what you want to do, but just using the INSERT statement is not possible, however it is possible to condition the insertion of data into a table, if this data is dependent on another table or comes from another table ... check here... SQL Insert explain in wikipedia
like this:
Copying rows from other tables
INSERT INTO phone_book2
SELECT *
FROM phone_book
WHERE name IN ('John Doe', 'Peter Doe')
or
INSERT INTO phone_book2 ( [name], [phoneNumber] )
SELECT [name], [phoneNumber]
FROM phone_book
WHERE name IN ('John Doe', 'Peter Doe')
Based on your question I have the feeling that you are trying to UPDATE a column in a table rather than insert.
Something like:
UPDATE column SET value WHERE different_column_value = some_value
I know this is kinda late, for those who still want to use the where clause in an insert query, it's kinda possible with a hack.
My understanding is that, you want to insert only if a condition is true. Let's assume you have a column in your database "surname" and you want to insert only if a surname doesn't exist from the table.
You kinda want something like INSERT INTO table_name blha blha blah WHERE surname!="this_surname".
The solution is to make that cell unique from your admin panel.
Insert statement will insert a new record. You cannot apply a where clause to the record that you are inserting.
The where clause can be used to update the row that you want.
update SET = where .
But insert will not have a where clause.
Hope this answers your question
INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.
I take it the code you included is simply a template to show how you structured your query. See the SO questions here, here and the MSDN question here.
In SQL Server (which uses Transact-SQL aka T-SQL) you need an UPDATE query for INSERT where columns already have values - by using the answer #HaveNoDisplayName gave :)
If you are executing INSERT / UPDATE from code (or if you need it regularly) I would strongly recommend using a stored procedure with parameters.
You could extend the procedure further by adding an INSERT block to the procedure using an IF-ELSE to determine whether to execute INSERT new record or UPDATE an existing, as seen in this SO answer.
Finally, take a look at SQLFiddle for a sandbox playground to test your SQL without risk to your RDMS :-)
Private case I found useful: Conditional insert which avoids duplications:
-- create a temporary table with desired values
SELECT 'Peter' FirstName, 'Pan' LastName
INTO #tmp
-- insert only if row doesn't exist
INSERT INTO Persons (FirstName, LastName)
SELECT *
FROM #tmp t
WHERE NOT EXISTS (SELECT * FROM Persons where FirstName=t.FirstName and LastName=t.LastName)
If the data need to be added for a column for an existing row then it’s UPDATE.
INSERT is creating a new row in the table.
For conditional INSERT, you can use the MERGE command.

Need Help using a loop to perform a mass insert in SQL

First off, i should say up front that i am not a very strong SQL person, so please be gentle :)
I need to perform about 400 inserts into a particular table. The data that i will be using for these inserts, i can collect from a SELECT statement that runs off a different table. I only need the data from 1 column from this table.
So, im hoping someone can help me write the SQL that will basically take the list of id's that are returned from my select, and use that list to do a mass insert into another table.
In psuedocode, something like this:
Select BankID from BankTable; - this returns 300 rows
Insert Into AccountTable -- this will add all 300 rows into the 2nd table
Values
(BankID)
thanks in advance guys...
Very simple, you basically said it. :-)
INSERT Into AccountTable (BankId, SecondColumn) SELECT BankId,'XXX' as staticText FROM BankTable;
It can be done in one statement:
Insert Into AccountTable (bankid)
Select BankID from BankTable
This assumes that the column in AccountTable is also named bankid; if not, just set the name appropriately in the parenthesis.
Keep in mind your INSERT statement must include the columns if the select statement does not match your table definition precisely.
INSERT AccountTable (BankID)
SELECT BankID
FROM BankTable
For multiple columns simply include the column list:
INSERT AccountTable (BankID, BankName)
SELECT BankID, BankName
FROM BankTable
You can also run into type conversion issues if the data types of the columns don't match (i.e. integer fields won't take alpha characters, etc.), but it is not a necessity that the column names match. Just get the order of columns and types right and you should be good.

How can i use INSERT as subquery in SELECT statement in sqlite?

I want something like this. But I dont know the proper syntax.
select id from table1
where name = (insert into table1 (name) values ('value_abcd'))
So you have a table with an autoincrementing primary key, and you want to know its value after you have inserted a record.
In SQL, you can use the last_insert_rowid function:
INSERT INTO table1(name) VALUES('value_abcd');
SELECT last_insert_rowid();
However, in most cases you do not need to execute a separate SELECT query because most libraries have some function to return that value.
For example, SQLite's C API has the sqlite3_last_insert_rowid function, and Android's insert function returns the ID directly.
When you say:
WHERE something = somethingElse
somethingElse is an expression (so is something, but anyway). You are trying to use an INSERT statement as your somethingElse, but an INSERT statement doesn't return anything, so it can not be evaluated as an expression. Therefore, not only is whatever you're trying to invalid syntax, it also doesn't make any sense in a pseudo-code kind of way.
Perhaps if you can try to explain more clearly what it is you're trying to do (and why), someone will be able to suggest something for you.
If id column of the table is set as identity, then in SQL
insert into table1(name) value('name')
select SCOPE_IDENTITY()
It will return last auto generated idetity value
If id column is not set as identity then in SQL
insert into table1(name)
output inserted.id
value('name')
It will return all id values inserted in a single statement.

insert data in multiple tables

hi i have a problem to insert data in multiple tables. i have define primary key & reference key in tables now i want to insert data in both tables in single query.......how can i do this...........???????
Your question isn't exactly clear on what the particular problem is. I can see three possibilities:
1. You want to insert into two tables wiht a single INSERT statement
2. You want to do two inserts, but without anything else being able to 'get in the middle'
3. You want to insert into one table, then get the primary key to insert into the second table
The answer to 1. is simple:
You can't.
The answer to 2. is simple too:
BEGIN TRANSACTION
INSERT INTO <table1> (a,b,c) VALUES (1,2,3)
INSERT INTO <table2> (a,b,c) VALUES (1,2,3)
COMMIT TRANSACTION
The answer to 3. is has several possibilities. Each depending on exactly what you want to do. Most likely you want to use SCOPE_IDENTITY() but you may also want to look up ##identity and IDENT_CURRENT() to understand the various different options and complexities.
BEGIN TRANSACTION
INSERT INTO <dimension_table> (name)
VALUES ('my new item')
INSERT INTO <fact_table> (item_id, iteam_value)
VALUES (SCOPE_IDENTITY(), 1)
COMMIT TRANSACTION
This is what transactions are meant for. Standard SQL does not permit a single statement inserting into multiple tables at once. The correct way to do it is:
-- begin transaction
insert into table 1 ...
insert into table 2 ...
commit
Does your language support the INSERT ALL construct? If so, that is the best way to do this. In fact it's the only way. I posted an example of this construct in another SO thread (that example syntax comes from Oracle SQL).
The other option is to build a transactional stored procedure which inserts a record into the primary key table followed by a record into the referencing table.
And 1 of your choice to do that is use ORM (like Hibernate, NHibernate) the you make your object and set other relation to it and finally just save the main object , like:
A a;
B b;
C c;
a.set(b);
a.set(c);
DAO.saveOrUpdate(a);
you must notice your DAO.saveOrUpdate(a); line of code just work with hibernate but it insert data into 3 table A, B, C.