views:

44

answers:

3

what i am trying to do is this:

INSERT INTO Table1 (id1, id2)
(
    SELECT id, 1 as id2 FROM Table2
)

except i CANNOT put '1 as id2' inside that select statement.

so, as an example, i sort of want this:

INSERT INTO Table1 (id1, id2 = 1)
(
    SELECT id FROM Table2
)

i'm putting this in a stored proc and the select statement is generated by linq2sql (passed as a text variable). I'd be happy to somehow get that 'id2' into the linq2sql command text, however the sql generated (correctly) only ever puts the actual Table2 columns in the query (being just 'id1').

and i really don't want to have to do some string formatting to insert the text ', 1 as id2' in the sql command text..

also i can't leave id2 as null as it's got a FK constraint on it.

A: 
INSERT INTO Table1 (id1, id2) SELECT id, 1 as id2 FROM Table2
Dmytrii Nagirniak
er.. i said 'i CANNOT put '1 as id2' inside that select statement'
benpage
A: 

ok got it:

create table #tmp
( id1 int)

insert into #tmp (id1)
(
    select top 10 id1 from Table1
)

insert into Table2 (id1, id2) 
(
    select id1, 5 from #tmp
)

drop table #tmp
benpage
+3  A: 

You can use your own sql with minor edit.

INSERT INTO Table1 (id1, id2)
(
    SELECT id, 1 FROM Table2
)
RJ1516