14

我需要将这些选择的值插入到表中。它们返回许多行,对于每一行,我需要在新表中插入一列。

前任:

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)

已编辑

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' 附近的语法不正确。”

4

1 回答 1

29

除非我遗漏了什么,否则您应该能够做到这一点:

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
于 2013-01-09T11:06:22.843 回答