metadata insert - sql-server-2008

I need to insert metadata values in a temp table. what is the easites thing to do it?
I have values like 3390,3391,8978,9899,7677,9656,5463 about 30-40 of them. I want to insert them into a temp table. Do not want to query a table since that is a big table and using an IN operator is very low in performance.
IS this the best way?
INSERT INTO #Table
Select '3390'
UNION ALL
select '3391'
UNION ALL
select '8978'
Any other suggetions?

It could be bit easier this way;
Insert into #temp (field)
select number
from (values (123),(456),(678),...,(432)) as t(number)
Or search for a split function and do it like;
insert into #temp (field)
select item from dbo.split('123,456,789',',')
To create and insert at the same time, you could use 'Select Into' syntax.

Related

How to merge 2 tables in mySQL [duplicate]

I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this:
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES
(SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);
I tried but get a syntax error message.
What would you do if you want to do this?
No "VALUES", no parenthesis:
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;
You have two syntax options:
Option 1
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
CREATE TABLE Table2 (
id int identity(1, 1) not null,
LongIntColumn2 int,
CurrencyColumn2 money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
INSERT INTO Table2
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1
Option 2
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1
INTO Table2
FROM Table1
GROUP BY LongIntColumn1
Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).
Remove both VALUES and the parenthesis.
INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1
I believe your problem in this instance is the "values" keyword. You use the "values" keyword when you are inserting only one row of data. For inserting the results of a select, you don't need it.
Also, you really don't need the parentheses around the select statement.
From msdn:
Multiple-record append query:
INSERT INTO target [(field1[, field2[, …]])] [IN externaldatabase]
SELECT [source.]field1[, field2[, …]
FROM tableexpression
Single-record append query:
INSERT INTO target [(field1[, field2[, …]])]
VALUES (value1[, value2[, …])
Remove VALUES from your SQL.
Remove "values" when you're appending a group of rows, and remove the extra parentheses. You can avoid the circular reference by using an alias for avg(CurrencyColumn) (as you did in your example) or by not using an alias at all.
If the column names are the same in both tables, your query would be like this:
INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn) as CurrencyColumn1
FROM Table1
GROUP BY LongIntColumn;
And it would work without an alias:
INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn)
FROM Table1
GROUP BY LongIntColumn;
Well I think the best way would be (will be?) to define 2 recordsets and use them as an intermediate between the 2 tables.
Open both recordsets
Extract the data from the first table (SELECT blablabla)
Update 2nd recordset with data available in the first recordset (either by adding new records or updating existing records
Close both recordsets
This method is particularly interesting if you plan to update tables from different databases (ie each recordset can have its own connection ...)
inserting data form one table to another table in different DATABASE
insert into DocTypeGroup
Select DocGrp_Id,DocGrp_SubId,DocGrp_GroupName,DocGrp_PM,DocGrp_DocType
from Opendatasource( 'SQLOLEDB','Data Source=10.132.20.19;UserID=sa;Password=gchaturthi').dbIPFMCI.dbo.DocTypeGroup
Do you want to insert extraction in an existing table?
If it does not matter then you can try the below query:
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 INTO T1 FROM Table1
GROUP BY LongIntColumn1);
It will create a new table -> T1 with the extracted information

Pulling an data from a nested INSERT statement using SELECT?

Is it possible to have an INSERT statement return the columns affected into a SELECT statement?
For example, I have the statement:
INSERT INTO work_day (WorkDateId, TimeframeId) VALUES (#selecteddateid,#timeframeid);
But work_day has an auto incrementing, work_dayId, that gets created when this row data is inserted. I want to put this work_dayId in another statement, but I was wondering if it would be able to nest this INSERT inside a SELECT that will select the affected/created row.
So would I be able to place this statement like so:
INSERT INTO appointment
(customerid, WorkDayId, UserId, Priority, Assign)
VALUES
(#otherdata
(SELECT WorkDayId FROM work_day WHERE WorkDateId = (INSERT INTO work_day (WorkDateId, TimeframeId) VALUES (#selecteddateid,#timeframeid))));
AS #Gordon stated:
No, you cannot do that. You want last_insert_id()
Posting it here as an answer for better visibility.

MySQL insert - for each row, return insert id

Let's say I have an array of data to insert. I'm going to have an insert that looks like this:
INSERT INTO `table` (`name`, `value`) VALUES('name1','value1'),('name2','value2')
We're assuming that table has a primary key.
Is there a way to, while batch inserting like this, grab the last insert id for each row, and return the those new ids? I know you can't do this traditionally with LAST_INSERT_ID(), but I'm wondering if I could use something like a cursor to achieve this functionality, and maybe a temporary table to store the values until I return them.
Any help would be great.
https://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
LAST_INSERT_ID() will return the first id from a multi row insert.
So you can just return that value and:
INSERT INTO `table1` (`name`, `value`) VALUES('name1','value1'),('name2','value2');
SET #firstid := LAST_INSERT_ID();
SELECT * from table1 where id>=#firstid;

INSERT INTO with SubQuery MySQL

I have this Statement:
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));
I'm trying to insert a value copy the same data of item_costprice, but show me the error:
Error Code: 1136. Column count doesn't match value count at row 1
How i can solve this?
Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
SELECT
/* Literal number values with column aliases */
1 AS item_code,
2 AS invoice_code,
item_costprice
FROM qa_items
WHERE item_code = 1;
Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.
You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
((SELECT id FROM modules WHERE title="Top bar"),0,-100);
I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.
Your insert statement contains too many columns on the left-hand side or not enough columns on the right hand side. The part before the VALUES has 7 columns listed, but the second part after VALUES only has 3 columns returned: 1, 2, then the sub-query only returns 1 column.
EDIT: Well, it did before someone modified the query....
As a sidenote to the good answer of Michael Berkowski:
You can also dynamically add fields (or have them prepared if you're working with php skripts) like so:
INSERT INTO table_a(col1, col2, col3)
SELECT
col1,
col2,
CURRENT_TIMESTAMP()
FROM table_B
WHERE b.col1 = a.col1;
If you need to transfer without adding new data, you can use NULL as a placeholder.
If you have multiple string values you want to add, you can put them into a temporary table and then cross join it with the value you want.
-- Create temp table
CREATE TEMPORARY TABLE NewStrings (
NewString VARCHAR(50)
);
-- Populate temp table
INSERT INTO NewStrings (NewString) VALUES ('Hello'), ('World'), ('Hi');
-- Insert desired rows into permanent table
INSERT INTO PermanentTable (OtherID, NewString)
WITH OtherSelect AS (
SELECT OtherID AS OtherID FROM OtherTable WHERE OtherName = 'Other Name'
)
SELECT os.OtherID, ns.NewString
FROM OtherSelect os, NewStrings ns;
This way, you only have to define the strings in one place, and you only have to do the query in one place. If you used subqueries like I initially did and like Elendurwen and John suggest, you have to type the subquery into every row. But using temporary tables and a CTE in this way, you can write the query only once.

3 different Insert into #table select in parallel SQL Server 2008

I have 1 temporary table and I am doing something like:
Insert into #table1 select ... from #temporal
Insert into #table2 select ... from #temporal
Insert into #table3 select ... from #temporal
As every select take a considerable time I would like to paralelize these 3 queries is there any way to do this in SQL Server 2008?
It sounds like the root of the problem is that the SELECT from #temporal is a performance problem. Do you have an index on that temp table #temporal? Likely an index (or statistics update) would help you out to avoid writing more code to work around this problem.
Are you able, or have you tried measuring performance against storing the results from that one #temporal SELECT into a table variable?
DECLARE #myTemporal TABLE (id int, foo varchar(100))
INSERT INTO #myTemporal (id, foo)
SELECT id, foo FROM #temporal;
Then your n INSERTs can pull from the table variable, rather than the expensive/nonperformant query.
Insert into #table1 select id, foo from #myTemporal;
Insert into #table2 select id, foo from #myTemporal;
Insert into #table3 select id, foo from #myTemporal;
The benefit is that you won't have to execute the SELECT 3x against your temp table. You'd be inserting into your 3 temp tables from the table variable. All rows, no WHERE clause.