Question

I am trying to do an insert using values from other tables AND constants. I have found partial answer on SO but i can't manage to finish the stored procedure. I should be doing something like

INSERT INTO table1(value1, value2, value3, value4)
SELECT 
    @value1,
    value2,
    value3,
    @value4 
FROM table2 WHERE table2.id = @value2; -- not sure

But i must use some kind of join to get data from the 3rd table as well and i don't know how.

I have 3 tables. i want to insert like this

INSERT INTO table1(field1, field2, field3, field4)

As for values

field1 = @field1
SELECT field2_type FROM table2 WHERE field2ID = @field2 -- field2
SELECT field3_type FROM table3 WHERE field3ID = @field3 -- field3
field4 = @field4

I am using SQL Server 2012

table1 looks like:

ID       int, PK
Name     varchar
Function int
Type     int
Age      int

table2 looks like:

FunctionID           int
FunctionDescription  varchar

table3 looks like:

TypeID               int
TypeDescription      varchar
Was it helpful?

Solution 2

I managed to find the answer. In case someone else is looking for it:

INSERT INTO table1(field1, field2, field3, field4)
select
field1 = @field1,
field2=  (SELECT TOP 1 field2_type FROM table2 WHERE field2ID = @field2 order by (select NULL)),
field3 = (SELECT TOP 1 field3_type FROM table3 WHERE field3ID = @field3 order by (select NULL)),
field4 = @field4

OTHER TIPS

very unclear what you said but use UNION if you want get all or use JOIN

INSERT INTO table1
SELECT *
FROM table2 
UNION
SELECT * FROM table3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top