除非我遗漏了什么,否则您应该能够做到这一点:
insert into Table (IDclient,NewName,IDRole,Initials)
select (select id from X where name=Contacts.Company) as IDClient,
FirstName + right(' '+ cast(LastName as varchar(20)), 20) as NewName,
(select id from Y where newid=8 and description=Contacts.JobTitle) as IDRole,
Initials
from Contacts
您将只使用INSERT INTO...SELECT...FROM..
语法。
现在,如果您没有表,那么您可以SELECT..INTO
创建一个新的临时表:
select (select id from X where name=Contacts.Company) as IDClient,
FirstName + right(' '+ cast(LastName as varchar(20)), 20) as NewName,
(select id from Y where newid=8 and description=Contacts.JobTitle) as IDRole,
Initials
into #table
from Contacts
或者,如果您想为此使用联接,则:
insert into Table (IDclient,NewName,IDRole,Initials)
select x.id as IDClient,
c.FirstName + right(' '+ cast(c.LastName as varchar(20)), 20) as NewName,
y.id as IDRole,
c.Initials
from Contacts c
inner join x
on x.name=c.Company
inner join y
on y.description=c.JobTitle
and y.newid=8
现在您的原始帖子显示了以下内容:
insert into Table (IDclient,NewName,'',IDRole,Initials,NULL)
您有两个没有名称的字段,这是不正确的语法。在您的插入语句中,要么必须命名任何列并插入全部,要么命名要插入值的列。您不能使用空字符串''
或null
作为列名。如果要插入这些值,则必须为它们提供名称:
insert into Table (IDclient,NewName,col3,IDRole,Initials,col5)
select x.id as IDClient,
c.FirstName + right(' '+ cast(c.LastName as varchar(20)), 20) as NewName,
'' as col3
y.id as IDRole,
c.Initials,
null as col5
from Contacts c
inner join x
on x.name=c.Company
inner join y
on y.description=c.JobTitle
and y.newid=8
根据您的编辑,您需要使用以下内容:
-- this insert line should state column names not '0', '0', etc
-- replace these with the names of your columns you are inserting into like the others,
-- then place these values that you want to insert in the select list
insert into TableX (IDClient,NewName,IDRole,'0','0','0',Initials,'XXX',GETDATE(),NULL,NULL)
select
(select id from X where nAme=Contacts.Company) as IDClient,
FirstName + right(' '+ cast(LastName as varchar(20)), 20) as NewName,
(select id from Y where newid=8 and description=Contacts.JobTitle) as IDRole,
'0',
'0',
'0',
Initials,
'XXX',
getdate(),
null,
null
from Contacts