Wrting Sql insert into statement using select statement - sql

I want to insert some values to a table (item1) from a table (item2) and date which is not in that item2 table.
How do I write a SQL insert into statement using the select statement to achieve that?
eg :
INSERT into item1(date, name, qty)
values(datevalue, select col1, col2 from item2);
This isn't working. What should I do to fix it?
insert into daily_stock(date, product_id, name, weight, qty, free_issues, sales_price,
purchased_price, category, last_purchased_date)
select
**'"+today+"'**,
productId, name, weight, newQty, freeIssues, NewSalesPrice,
NewPurchasePrice, category, datePurchased
from product
I'm using java and today is a string variable , still data is not inserting , whats wrong?

you're almost there: just use the SELECT variation for INSERT instread of VALUES, and include your data there as a constant:
insert into item1(date,name,qty)
select <datevalue>, col1, col2 from item2;
If your date comes from another table, you can do this:
insert into item1(date,name,qty)
select d.dcol1, i2.col1, i2.col2
from item2 i2 inner join table_containing_date_col d
on <some join criteria>
EDIT: you have to ensure that the data types match i.e. your has to be parsable to a date if you are savign it to a date field (which you are, hopefully!). You don't give details of your database but it would be something like this for SQL Server
cast('your date in yyyymmdd format' as datetime)
(yyyymmdd always works as it is recognisable ISO format)
or better still CONVERT
For MySql you have STR_TO_DATE, for Oracle TO_DATE etc.etc.

use INSERT INTO...SELECT statement
INSERT INTO item1 (date, name, qty)
SELECT 'value here' as datevalue, col1, col2
FROM item2

In the absence of a specific SQL server/type you are using, in T-SQL this can be done like so:
INSERT INTO Table1
SELECT '29/01/2012', T2.Column1, T2.Column2 FROM Table2 T2

You are close.
INSERT into ITEM1 (date, name, qty)
values (datevalue, (SELECT col1, col2 FROM item2));

Related

SELECT values of an INSERT INTO statement

I need to select a few columns from a table1. I need to insert only one of these columns as well as some arbitrary hard coded data and insert it into table2 while also getting the original select statement back.
Basically I would like to get the results of my INSERT INTO statement instead of the "(1 row(s) affected)" that I get in SSMS.
Is there a way to do this?
Here is a SQLFiddle:
http://sqlfiddle.com/#!3/e9beb/3
Those records will insert just fine. However, I want the results of my SELECT statement to come back to me so that I can do it all at once without multiple reads or trips. Is this possible?
You can use the OUTPUT clause:
INSERT INTO Table2
OUTPUT inserted.*
SELECT Phrase, 'This is an automatic note by the system', GETDATE(), 1
FROM Table1
Use a batch statement and store the intermediate results in a table variable:
DECLARE #intermediate TABLE (
col1 type,
col2 type,
col3 type
);
INSERT INTO #intermediate VALUES ( ... );
INSERT INTO destinationTable SELECT * FROM #intermediate;
SELECT #intermediate;
If using this from code you can have all of this in a single command-text string.
Have you tried something like this:
INSERT INTO Table1 (
SELECT Phrase, Notes, GetDate, 1
FROM Table2
UNION
SELECT Phrase, 'This is an automatic note by the system', GETDATE(), 1
UNION
)

Insert distinct values from one table into another table

So for each distinct value in a column of one table I want to insert that unique value into a row of another table.
list = select distinct(id) from table0
for distinct_id in list
insert into table1 (id) values (distinct_id)
end
Any ideas as to how to go about this?
Whenever you think about doing something in a loop, step back, and think again. SQL is optimized to work with sets. You can do this using a set-based query without the need to loop:
INSERT dbo.table1(id) SELECT DISTINCT id FROM dbo.table0;
There are some edge cases where looping can make more sense, but as SQL Server matures and more functionality is added, those edge cases get narrower and narrower...
insert into table1 (id)
select distinct id from table0
The following statement works with me.
insert into table1(col1, col2) select distinct on (col1) col1 col2 from table0
The below query will also check the existing data in the Table2.
INSERT INTO Table2(Id) SELECT DISTINCT Id FROM Table1 WHERE Id NOT IN(SELECT Id FROM Table2);
Other Simple way to copy distinct data with multiple columns from one table to other
Insert into TBL2
Select * from (Select COL1, ROW_NUMBER() over(PARTITION BY COL1 Order By COL1) AS COL2 From TBL1)T
where T.COL2 = 1

adjusting the insert into SQL

I got this already working;
INSERT INTO TermsFinal
(old_classification, count, new_classification, old_term,new_term)
SELECT old_classification , Count(seed) AS count , new_classification, old_term, new_term FROM TermsTemp
GROUP BY old_classification
ORDER BY count DESC
There is one more field in the TermsFinal called SOURCE_TABLE which TermsTemp does not have.
I would like to populate that field too. I already got the $source_table value. I tried this but dis not work.
INSERT INTO TermsFinal
(SOURCE_TABLE,old_classification, count, new_classification, old_term,new_term)
'{$SOURCE_TABLE}', SELECT old_classification , Count(seed) AS count , new_classification, old_term, new_term FROM TermsTemp_TEMP
GROUP BY old_classification
ORDER BY count DESC
How do you add that value into the SOURCE_TABLE field of the TermsFinal while executing the insert into statement in one go?
and the other puzzling thing to me here, how come my first SQL insertinto works without the SQL keyword VALUES. This page http://www.w3schools.com/sql/sql_insert.asp teaches that VALUES part is needed!
You can put string (or any other type ) constant into select, for example
select 'string' as const_str , field1 from table1 will return 2 columns , the first will have "string" text for all rows. In your case you can do
INSERT INTO TermsFinal
(SOURCE_TABLE,old_classification, count, new_classification, old_term,new_term)
SELECT '{$SOURCE_TABLE}', old_classification , Count(seed) AS count , new_classification, old_term, new_term FROM TermsTemp_TEMP
GROUP BY old_classification
ORDER BY count DESC
There are several ways to insert data into a table
One row at a time. This is where you need the values keyword.
Insert into TableA (Col1, Col2,...) values (#Val1, #Val2,...)
You can get the id using select ##identity (at least in ms sql), if you have auto identity
on. This is useful when you need the ID for you next insert.
From select (what you're doing)
Insert into tableA (Col1, Col2)
Select Val1, Val2 from TableB
or insert a hard coded value and values from two separate tables
Insert into tableA (Col1, Col2, Col3, Col4)
Select 'hard coded value', b.Val1, b.Val2, c.Val1
from TableB b join Table c on b.TableCID=c.ID
Now you can insert more than one row at once.
Select into
This method ends up creating a new table from a query, and is great for quick backups of a table, or part of a table.
select * into TermsFinal_backup from TermsFinal where ...

How to select the record from table and insert into another table?

I wanted to select the last record from the table1 and insert into another table .Here is my query.
Insert into table2 values(select top 1 col1,col2 from table1 order by id desc).
I know for adding the value into table,need to be in cotation.But where to add?
You can select literals to fill in the other columns that table1 can't provide, something like this:
insert into table2 (col_a, col_b, col_c, col_d)
select top 1 col1, col2, 'foo', 'bar'
from table1
order by id desc
Any columns you do not name in the column list will get the default value, or null if no default is defined.
The number and type of columns selected must match the number and type of columns in the insert column list.
In SQL, there are essentially basically two ways to INSERT data into a table: One is to insert it one row at a time, the other is to insert multiple rows at a time. Let's take a look at each of them individually:
INSERT INTO table_name (column1, column2, ...)
VALUES ('value1', 'value2', ...)
The second type of INSERT INTO allows us to insert multiple rows into a table. Unlike the previous example, where we insert a single row by specifying its values for all columns, we now use a SELECT statement to specify the data that we want to insert into the table. If you are thinking whether this means that you are using information from another table, you are correct. The syntax is as follows:
INSERT INTO table1 (column1, column2, ...)
SELECT t2.column3, t2.column4, ...
FROM table2 t2
So, in you case, you can do it like this:
Insert into table2
select top 1 t1.col1,t1.col2 from table1 t1 order by id desc
Or you can use your syntax like this:
declare #col1 type_of_col1, #col2 type_of_col2
select top 1 #col1 = t1.col1, #col2 = t1.col2 from table1 t1 order by id desc
Insert into table2 values(#col1, #col2)
Offcourse, this all works assuming that the column datatypes are matched.

Is this possible with sql?

Is it possible to do something like this:
INSERT INTO table(col1, col2) VALUES(something_from_another_table, value);
With something_from_another_table being a SQL command? Like, is there something I can do that's equivelant to:
INSERT INTO table(col1, col2) VALUES((SELECT value FROM table2 WHERE id = 3), value);
Yes
INSERT INTO table(col1, col2)
SELECT value1, 'value2' FROM table2 WHERE id = 3
Where value1 is the value from the 'other table' and value2 is a constant that you've included in that select statement.
Try this:
INSERT INTO table(col1, col2)
SELECT table2.value1, value2 FROM table2 WHERE table2.id = 3;
http://dev.mysql.com/doc/refman/5.1/en/insert-select.html
take a look especially in the examples.
I would recommend reading full syntax of SELECT, UPDATE, DELETE and INSERT SQL commands to begin with. Then expand to subqueries and DDL.
Go slowly and work out examples.
You definately can. It should work similar as the example below;
INSERT INTO Store_Information (store_name, Sales, Date)
(SELECT store_name, Sales, Date FROM Sales_Information WHERE Year(Date) = 2010)
when you specify the keyword "Values" on the insert statement you are trying to insert just a value. the current way to do that is assigning the value of the "something_from_another_table" into a variable and then, make your insert
DECLARE #ANYVALUE AS VARCHAR(40)
SELECT #ANYVALUE = ANYFIELD FROM table2 WHERE id = 3
INSERT INTO table1 (FIELD1, FIELD2) VALUES(#ANYVALUE, VALUE2)
On this way always will insert one record. the other correct way will insert n record as the where statement can filter.
INSERT INTO Store_Information (store_name, Sales, Date)
(SELECT store_name, Sales, Date FROM Sales_Information WHERE Year(Date) = 2010)