SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Insert by selecting multiple columns
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

barnabeck
Posting Yak Master

Spain
194 Posts

Posted - 03/14/2013 :  12:42:30  Show Profile  Reply with Quote
I have to insert n-records based on a query and have to assign 7 values, comming from a second query.

Insert into table1 (ID, column1, column2,..., column7)
values (@ID, @column1, @column2,..., column7)

Query1 returns the ID (Format vector:1 x n)
Query2 returns the values for column1-7 (Format vector: 7 x 1) which do not vary for the n records

The correct matrix of values (Format 7 x n) is described by:

SELECT a.ID, b.column1, b.column2,..., b.column from
(SELECT ID from TABLE2) a
JOIN
(SELECT column1, column2,..., column7 from TABLE3) b on a.ID <> '0'

Unfortunatly I can't place this query into the INSERT clause like
Insert into table1 (ID, column1, column2,..., column7)
           values ((SELECT a.ID, b.column1, b.column2,..., b.column from
                   (SELECT ID from TABLE2) a
                    JOIN
                   (SELECT column1, column2,..., column7 from TABLE3) b on a.ID <> '0'))
It throws 2 errors:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
and (this is NOT true):
There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.

Any comment on that?
Regards,
Martin

TG
Flowing Fount of Yak Knowledge

USA
6062 Posts

Posted - 03/14/2013 :  14:33:38  Show Profile  Reply with Quote
Two common ways to insert into a table are through: INSERT VALUES and INSERT SELECT
So pick one or the other and don't try to combine them. The select method can be any valid select statement. So assuming the statement that you have inside the values() returns rows that match the column list of your insert into list then just remove the "values()" part.

insert into table1 (<columnList>)
select <sameColumnList>
from ....


Be One with the Optimizer
TG
Go to Top of Page

barnabeck
Posting Yak Master

Spain
194 Posts

Posted - 03/14/2013 :  17:13:41  Show Profile  Reply with Quote
Thank you, I will try this out later, because it became secondary as I need to combine the input with an update and I'm having a problem I will start another thread on.

Martin
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000