我需要将这些选择的值插入表中。 它们返回许多行,对于每一行,我需要将一列插入到新表中。
例如:
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 TableX (IDClient,NewName,IDRole,'0','0','0',Initials,'XXX',GETDATE(),NULL,NULL)
泰
EDITED
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,
Initials
from Contacts
当我执行此操作时,我收到此错误:
“'0'附近的语法不正确。”
答案 0 :(得分:15)
除非我遗漏了某些东西,否则你应该能够做到这一点:
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)
您有两个没有名称的字段,这是不正确的语法。在insert语句中,要么不指定任何列并插入所有列,要么将要插入值的列命名为。您不能使用空字符串''
或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