3

我想将此查询的结果插入到我在下面创建的表中。

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Entity]') AND type in (N'U'))
DROP TABLE [Entity]
Go
Create Table Entity

([EntCode] [nvarchar](8) NOT NULL,
    [Name] [nvarchar](80) NOT NULL,
    [CompanyRegistration] [nvarchar](80) NULL,
    [Active] [int] NOT NULL,
    [AccessLevel] [int] NOT NULL ,
    [SiteURN] [nvarchar](128) NOT NULL,
    [CompanyURN] [nvarchar](128) NOT NULL,
    [SiteName] [nvarchar](30) NOT NULL,
    [SiteDesc] [nvarchar](60) NULL,
    [SiteURL] [nvarchar](512) NOT NULL)

我想使用这个从这个查询中插入数据,但是我收到这个错误“插入错误:列名或提供的值的数量与表定义不匹配”

因为我有一个额外的列 [CompanyRegistration] nvarchar NULL,我在创建表时将其标记为 NULL。如何使用表中标记为 NULL 的 [CompanyRegistration] 列插入这些查询结果?

insert into ResourceTaskFact.dbo.Entity

Select
    e.EntCode,
    e.Name,
    e.Active ,
    e.AccessLevel, 

    ss.SiteURN,
    ss.CompanyURN, 
    ss.SiteName ,
    ss.SiteDesc ,
    ss.SiteURL 
from SMECSite ss, SMECLegalEnt e
where ss.localsiteflag = 1
and e.active = 1 

我该如何解决这个问题?我需要你的帮助伙计们。先感谢您!

4

3 回答 3

4
insert into ResourceTaskFact.dbo.Entity
  (e.EntCode,
   e.Name,
   e.Active,
   e.AccessLevel,
   ss.SiteURN,
   ss.CompanyURN,
   ss.SiteName,
   ss.SiteDesc,
   ss.SiteURL)

  Select e.EntCode,
         e.Name,
         e.Active,
         e.AccessLevel,
         ss.SiteURN,
         ss.CompanyURN,
         ss.SiteName,
         ss.SiteDesc,
         ss.SiteURL
    from SMECSite ss, SMECLegalEnt e
   where ss.localsiteflag = 1
     and e.active = 1
于 2013-09-23T10:35:05.387 回答
3

您需要在语句中明确设置CompanyRegistration为:NULLSELECT

insert into ResourceTaskFact.dbo.Entity

Select
    e.EntCode,
    e.Name,
    NULL AS CompanyRegistration, -- Put column name in to demonstrate why you're selecting NULL here
    e.Active ,
    e.AccessLevel, 
    ss.SiteURN,
    ss.CompanyURN, 
    ss.SiteName ,
    ss.SiteDesc ,
    ss.SiteURL 
from SMECSite ss, SMECLegalEnt e
where ss.localsiteflag = 1
and e.active = 1 
于 2013-09-23T10:32:53.810 回答
0

命名要插入的列是一个好习惯

insert into ResourceTaskFact.dbo.Entity 
(
    [EntCode], 
    [Name], 
    [Active],
    [AccessLevel],
    [SiteURN],
    [CompanyURN]L,
    [SiteName],
    [SiteDesc],
    [SiteURL]
)    
Select
    e.EntCode,
    e.Name,
    e.Active ,
    e.AccessLevel,     
    ss.SiteURN,
    ss.CompanyURN, 
    ss.SiteName ,
    ss.SiteDesc ,
    ss.SiteURL 
from SMECSite ss, SMECLegalEnt e
where ss.localsiteflag = 1
and e.active = 1 

这样你就不必填充你没有价值的列。

于 2013-09-23T10:32:04.487 回答