INSERT to a table with a sub query - sql

Can I do this in SQL 2005?
SELECT 'C'+inserted.exhid AS ExhId,inserted.exhname AS ExhName,inserted.exhid AS RefID INTO mytable FROM inserted
WHERE inserted.altname IS NOT NULL
It won't work if the table exists, but will create the table if it is non-existent. How do I get it to insert into an existing table?

like this
INSERT INTO mytable
SELECT 'C'+inserted.exhid AS ExhId,inserted.exhname AS ExhName,
inserted.exhid AS RefID FROM inserted
WHERE inserted.altname IS NOT NULL
you also don't need the aliases in this case

SQLMenace's answer is correct. But to add to it, I would suggest that it is a good practice to explicitly list your columns that you are inserting into in the event the table structure/column order ever changes, that way your proc stands a better change of working consistently.
INSERT INTO mytable (
ExhId,
ExhName,
RefID)
SELECT 'C'+inserted.exhid,
inserted.exhname,
inserted.exhid
FROM inserted
WHERE inserted.altname IS NOT NULL

To insert into an existing table, use INSERT INTO instead of `SELECT INTO

Related

How to copy some records of table and change some columns before insert into this table again in sql server?

In my SQL Server table, I have a table whose PK is GUID with lots of records already.
Now I want to add records which only needs to change the COMMON_ID and COMMON_ASSET_TYPE column of some existing records.
select * from My_Table where COMMON_ASSET_TYPE = "ASSET"
I am writing sql to copy above query result, changing COMMON_ID value to new GUID value and COMMON_ASSET_TYPE value from "ASSET" to "USER", then insert the new result into My_Table.
I do not know how to write it since now I feel it is a trouble to insert records manually.
Update:
I have far more columns in table and most of them are not nullable, I want to keep all these columns' data for new records except above two columns.Is there any way if I do not have to write all these column names in sql?
Try to use NEWID if you want to create new guid:
INSERT INTO dbo.YourTable
(
COMMON_ID,
COMMON_ASSET_TYPE
)
select NEWID(), 'User' as Common_Asset_Type
from My_Table
where COMMON_ASSET_TYPE = "ASSET"
UPDATE:
As a good practice I would suggest to write all column names explicitly to have a clean and clear insert statement. However, you can use the following construction, but it is not advisable in my opinion:
insert into table_One
select
id
, isnull(name,'Jon')
from table_Two
INSERT INTO My_Table (COMMON_ID,COMMON_LIMIT_IDENTITY, COMMON_CLASS_ID,COMMON_ASSET_TYPE)
SELECT NEWID(), COMMON_LIMIT_IDENTITY, COMMON_CLASS_ID,'USER'
FROM My_Table
WHERE COMMON_ASSET_TYPE = 'ASSET'
If I've understood correctly you want to take existing records in your table, modify them, and insert them as new records in the same table.
I'll assume ID column contains the the GUID?
I'd first create a temporary table
CREATE TABLE #myTempTable(
ID UNIQUEIDENTIFIER,
Name varchar(max),
... etc
);
Fill this temp table with the records to change with your SELECT statement.
Change the records in the temp table using UPDATE statement.
Finally, Insert those "new" records back into the primary table. with INSERT INTO SELECT statement.
You will probably have to sandwitch the INSERT INTO SELECT with IDENTITY_INSERT (on/off):
SET IDENTITY_INSERT schema_name.table_name ON
SET IDENTITY_INSERT schema_name.table_name OFF
IDENTITY_INSERT "Allows explicit values to be inserted into the identity column of a table."

Select from inherited table

I have this inheritance in my database and I need to use a SELECT query and INSERT query to it.
I can't seem to pull this off.
It's about the Item and it's inheritances.
This could be helpful?
INSERT INTO table2
SELECT *
FROM table1
WHERE condition;
I don't know if i've understood your question but, you want to insert some values into a table selecting from an another table.

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.

"select * into table" Will it work for inserting data into existing table

I am trying to insert data from one of my existing table into another existing table.
Is it possible to insert data into any existing table using select * into query.
I think it can be done using union but in that case i need to record all data of my existing table into temporary table, then drop that table and finally than apply union to insert all records into same table
eg.
select * into #tblExisting from tblExisting
drop table tblExisting
select * into tblExisting from #tblExisting union tblActualData
Here tblExisting is the table where I actually want to store all data
tblActualData is the table from where data is to be appended to tblExisting.
Is it right method.
Do we have some other alternative ?
You should try
INSERT INTO ExistingTable (Columns,..)
SELECT Columns,...
FROM OtherTable
Have a look at INSERT
and SQL SERVER – Insert Data From One Table to Another Table – INSERT INTO SELECT – SELECT INTO TABLE
No, you cannot use SELECT INTO to insert data into an existing table.
The documentation makes this very clear:
SELECT…INTO creates a new table in the default filegroup and inserts the resulting rows from the query into it.
You generally want to avoid using SELECT INTO in production because it gives you very little control over how the table is created, and can lead to all sorts of nasty locking and other performance problems. You should create schemas explicitly and use INSERT - even for temporary tables.
#Ryan Chase
Can you do this by selecting all columns using *?
Yes!
INSERT INTO yourtable2
SELECT * FROM yourtable1
Update from CTE? http://www.sqlservercentral.com/Forums/Topic629743-338-1.aspx

MySQL Insert query doesn't work with WHERE clause

What's wrong with this query:
INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
It works without the WHERE clause. I've seemed to have forgot my SQL.
MySQL INSERT Syntax does not support the WHERE clause so your query as it stands will fail. Assuming your id column is unique or primary key:
If you're trying to insert a new row with ID 1 you should be using:
INSERT INTO Users(id, weight, desiredWeight) VALUES(1, 160, 145);
If you're trying to change the weight/desiredWeight values for an existing row with ID 1 you should be using:
UPDATE Users SET weight = 160, desiredWeight = 145 WHERE id = 1;
If you want you can also use INSERT .. ON DUPLICATE KEY syntax like so:
INSERT INTO Users (id, weight, desiredWeight) VALUES(1, 160, 145) ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145
OR even like so:
INSERT INTO Users SET id=1, weight=160, desiredWeight=145 ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145
It's also important to note that if your id column is an autoincrement column then you might as well omit it from your INSERT all together and let mysql increment it as normal.
You can't combine a WHERE clause with a VALUES clause. You have two options as far as I am aware-
INSERT specifying values
INSERT INTO Users(weight, desiredWeight)
VALUES (160,145)
INSERT using a SELECT statement
INSERT INTO Users(weight, desiredWeight)
SELECT weight, desiredWeight
FROM AnotherTable
WHERE id = 1
You use the WHERE clause for UPDATE queries. When you INSERT, you are assuming that the row doesn't exist.
The OP's statement would then become;
UPDATE Users SET weight = 160, desiredWeight = 45 where id = 1;
In MySQL, if you want to INSERT or UPDATE, you can use the REPLACE query with a WHERE clause. If the WHERE doesn't exist, it INSERTS, otherwise it UPDATES.
EDIT
I think that Bill Karwin's point is important enough to pull up out of the comments and make it very obvious. Thanks Bill, it has been too long since I have worked with MySQL, I remembered that I had issues with REPLACE, but I forgot what they were. I should have looked it up.
That's not how MySQL's REPLACE works. It does a DELETE (which may be a no-op if the row does not exist), followed by an INSERT. Think of the consequences vis. triggers and foreign key dependencies. Instead, use INSERT...ON DUPLICATE KEY UPDATE.
I do not believe the insert has a WHERE clause.
Insert query doesn't support where keyword*
Conditions apply because you can use where condition for sub-select statements.
You can perform complicated inserts using sub-selects.
For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE city = 'Newark';
By placing a "select" in the insert statement, you can perform multiples inserts quickly.
With this type of insert, you may wish to check for the number of rows being inserted. You can determine the number of rows that will be inserted by running the following SQL statement before performing the insert.
SELECT count(*)
FROM customers
WHERE city = 'Newark';
You can make sure that you do not insert duplicate information by using the EXISTS condition.
For example, if you had a table named clients with a primary key of client_id, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);
This statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);
The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.
See also How to insert with where clause
The right answer to this question will be sth like this:
a). IF want select before insert :
INSERT INTO Users( weight, desiredWeight )
select val1 , val2 from tableXShoulatNotBeUsers
WHERE somecondition;
b). IF record already exists use update instead of insert:
INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
Should be
Update Users set weight=160, desiredWeight=145 WHERE id = 1;
c). If you want to update or insert at the same time
Replace Users set weight=160, desiredWeight=145 WHERE id = 1;
Note):- you should provide values to all fields else missed field in query
will be set to null
d). If you want to CLONE a record from SAME table, just remember you cann't select
from table to which you are inserting therefore
create temporary table xtable ( weight int(11), desiredWeight int(11) ;
insert into xtable (weight, desiredWeight)
select weight, desiredWeight from Users where [condition]
insert into Users (weight, desiredWeight)
select weight , desiredWeight from xtable;
I think this pretty covers most of the scenarios
You simply cannot use WHERE when doing an INSERT statement:
INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
should be:
INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 );
The WHERE part only works in SELECT statements:
SELECT from Users WHERE id = 1;
or in UPDATE statements:
UPDATE Users set (weight = 160, desiredWeight = 145) WHERE id = 1;
A way to use INSERT and WHERE is
INSERT INTO MYTABLE SELECT 953,'Hello',43 WHERE 0 in (SELECT count(*) FROM MYTABLE WHERE myID=953);
In this case ist like an exist-test. There is no exception if you run it two or more times...
I think that the correct form to insert a value on a specify row is:
UPDATE table SET column = value WHERE columnid = 1
it works, and is similar if you write on Microsoft SQL Server
INSERT INTO table(column) VALUES (130) WHERE id = 1;
on mysql you have to Update the table.
Insert into = Adding rows to a table
Upate = update specific rows.
What would the where clause describe in your insert?
It doesn't have anything to match, the row doesn't exist (yet)...
You can do conditional INSERT based on user input.
This query will do insert only if input vars '$userWeight' and '$userDesiredWeight' are not blank
INSERT INTO Users(weight, desiredWeight )
select '$userWeight', '$userDesiredWeight'
FROM (select 1 a ) dummy
WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';
If you are looking to insert some values into a new column of an altered table in each rows by mentioning its primary key, then just-->
UPDATE <table_name> SET <column_name> = '<value> WHERE <primary_key> = <primary_value>
It depends on the situation INSERT can actually have a where clause.
For example if you are matching values from a form.
Consider INSERT INTO Users(name,email,weight, desiredWeight) VALUES (fred,bb#yy.com,160,145) WHERE name != fred AND email != bb#yy.com
Makes sense doesn't it?
The simplest way is to use IF to violate your a key constraint. This only works for INSERT IGNORE but will allow you to use constraint in a INSERT.
INSERT INTO Test (id, name) VALUES (IF(1!=0,NULL,1),'Test');
After WHERE clause you put a condition, and it is used for either fetching data or for updating a row. When you are inserting data, it is assumed that the row does not exist.
So, the question is, is there any row whose id is 1? if so, use MySQL UPDATE, else use MySQL INSERT.
If you are specifying a particular record no for inserting data its better to use UPDATE statement instead of INSERT statement.
This type of query you have written in the question is like a dummy query.
Your Query is :-
INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
Here , you are specifying the id=1 , so better you use UPDATE statement to update the existing record.It is not recommended to use WHERE clause in case of INSERT.You should use UPDATE .
Now Using Update Query :-
UPDATE Users SET weight=160,desiredWeight=145 WHERE id=1;
Does WHERE-clause can be actually used with INSERT-INTO-VALUES in any
case?
The answer is definitively no.
Adding a WHERE clause after INSERT INTO ... VALUES ... is just invalid SQL, and will not parse.
The error returned by MySQL is:
mysql> INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 1' at line 1
The most important part of the error message is
... syntax to use near 'WHERE id = 1' ...
which shows the specific part the parser did not expect to find here: the WHERE clause.
its totall wrong. INSERT QUERY does not have a WHERE clause, Only UPDATE QUERY has it. If you want to add data Where id = 1 then your Query will be
UPDATE Users SET weight=160, desiredWeight= 145 WHERE id = 1;
No. As far as I am aware you cannot add the WHERE clause into this query. Maybe I've forgotten my SQL too, because I am not really sure why you need it anyway.
You Should not use where condition in Insert statement. If you want to do, use insert in a update statement and then update a existing record.
Actually can i know why you need a where clause in Insert statement??
Maybe based on the reason I might suggest you a better option.
I think your best option is use REPLACE instead INSERT
REPLACE INTO Users(id, weight, desiredWeight) VALUES(1, 160, 145);
DO READ THIS AS WELL
It doesn't make sense... even literally
INSERT means add a new row and when you say WHERE you define which row are you talking about in the SQL.
So adding a new row is not possible with a condition on an existing row.
You have to choose from the following:
A. Use UPDATE instead of INSERT
B. Use INSERT and remove WHERE clause ( I am just saying it...) or if you are real bound to use INSERT and WHERE in a single statement it can be done only via INSERT..SELECT clause...
INSERT INTO Users( weight, desiredWeight )
SELECT FROM Users WHERE id = 1;
But this serves an entirely different purpose and if you have defined id as Primary Key this insert will be failure, otherwise a new row will be inserted with id = 1.
I am aware that this is a old post but I hope that this will still help somebody, with what I hope is a simple example:
background:
I had a many to many case: the same user is listed multiple times with multiple values and I wanted to Create a new record, hence UPDATE wouldn't make sense in my case and I needed to address a particular user just like I would do using a WHERE clause.
INSERT into MyTable(aUser,aCar)
value(User123,Mini)
By using this construct you actually target a specific user (user123,who has other records) so you don't really need a where clause, I reckon.
the output could be:
aUser aCar
user123 mini
user123 HisOtherCarThatWasThereBefore
correct syntax for mysql insert into statement using post method is:
$sql="insert into ttable(username,password) values('$_POST[username]','$_POST[password]')";
i dont think that we can use where clause in insert statement
INSERT INTO Users(weight, desiredWeight )
SELECT '$userWeight', '$userDesiredWeight'
FROM (select 1 a ) dummy
WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';
You can't use INSERT and WHERE together. You can use UPDATE clause for add value to particular column in particular field like below code;
UPDATE Users
SET weight='160',desiredWeight ='145'
WHERE id =1
You can do that with the below code:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition
I think you should do it like this, if you want to validate table not to use email twice
Code :
INSERT INTO tablename(fullname,email)
SELECT * FROM (SELECT 'fullnameValue' AS fullname_field,'emailValue' AS email_field) entry WHERE entry.email_field NOT IN (SELECT email FROM tablename);
All the above answers give you the plain MySQL statements.
If you are using the where condition in PHPMyAdmin to update the existing row of a table, below is the suggestion to use.
UPDATE `Table_Name` SET `row1`='[value-1]',`row2`='[value-2]',`row3`='[value-3]' WHERE 1
You can include any value between '' of each row. Not necessarily to put [] to indicate the value. Do not change anything after where. Simply click go after giving the value to update.
Example:
UPDATE `Mytable_name` SET `abc`='xyz',`def`='uvw'
WHERE 1