-- First, correct all the mistakes in your sample table script:
DROP TABLE table1
DROP TABLE table2
DROP TABLE table3
DROP TABLE table4
DROP TABLE table5
create table table1 (phone int,kod_name int ,kod_fname int,kod_country int,kod_auto int) --
create table table2 (name_ nvarchar(30),kod int)
insert into table2 values('james',1)
insert into table2 values('stivens',2)
insert into table2 values('carlos',3)
create table table3 (f_name nvarchar(30),kod int)
insert into table3 values('john',1)
insert into table3 values('tayson',2)
insert into table3 values('swarzneger',3)
create table table4 (country nvarchar(30),kod int)
insert into table4 values('argentina',1)
insert into table4 values('brazilia',2)
insert into table4 values('korea',3)
create table table5 (m_auto nvarchar(30),kod int)
insert into table5 values('mersedec',1)
insert into table5 values('jaguar',2)
insert into table5 values('landrover',3)
-- You want to see what's happening with your INSERT.
-- this query shows all of the rows and all of the columns
-- which would be inserted, along with the input data.
-- Stare & Compare: check that everything looks correct.
;WITH NewRowForTable1 AS (
SELECT
phone = '11111',
name_ = 'james',
fname = 'john',
country = 'korea',
[auto] = 'jaguar')
SELECT
n.phone,
n.name_, kod_name = t2.kod,
n.fname, kod_fname = t3.kod,
n.country, kod_country = t4.kod,
n.[auto], kod_auto = t5.kod
FROM NewRowForTable1 n
LEFT JOIN table2 t2 ON t2.name_ = n.name_
LEFT JOIN table3 t3 ON t3.f_name = n.fname
LEFT JOIN table4 t4 ON t4.country = n.country
LEFT JOIN table5 t5 ON t5.m_auto = n.[auto]
-- Solution
-- INSERT the new row
;WITH NewRowForTable1 AS (
SELECT
phone = '11111',
name_ = 'james',
fname = 'john',
country = 'korea',
[auto] = 'jaguar')
INSERT INTO table1 (
phone,
kod_name,
kod_fname,
kod_country,
kod_auto)
SELECT
n.phone,
kod_name = t2.kod,
kod_fname = t3.kod,
kod_country = t4.kod,
kod_auto = t5.kod
FROM NewRowForTable1 n
LEFT JOIN table2 t2 ON t2.name_ = n.name_
LEFT JOIN table3 t3 ON t3.f_name = n.fname
LEFT JOIN table4 t4 ON t4.country = n.country
LEFT JOIN table5 t5 ON t5.m_auto = n.[auto]
-- Check that the INSERT succeeded
SELECT * FROM table1
-- Check that the inserted data is correct
SELECT t1.phone, t2.name_, t3.f_name, t4.country, t5.m_auto
FROM table1 t1
LEFT JOIN table2 t2 ON t2.kod = t1.kod_name
LEFT JOIN table3 t3 ON t3.kod = t1.kod_fname
LEFT JOIN table4 t4 ON t4.kod = t1.kod_country
LEFT JOIN table5 t5 ON t5.kod = t1.kod_auto
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden