尝试合并两个不同表中的两个选择时出现错误

时间:2019-03-27 09:36:49

标签: sql-server tsql view union

所以我创建了一个专家小组,以重组来自两个表的信息(表A中存在信息,而表b中不存在这些信息,虎钳verca

USE [DATAWARHOUSE]
GO

/****** Object:  View [dbo].[GroupingCP]    Script Date: 3/27/2019 10:29:39 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


ALTER VIEW [dbo].[GroupingCP] AS

SELECT [CODFILIALE]
      ,[I_CODPRO]
      ,[CODICE]
      ,[RagioneSociale]
      ,[Indirizzo]
      ,[Cap]
      ,[Localita]
      ,[Provincia]
      ,[CodNazione]
      ,[DesNazione]
      ,[Telefono]
      ,[Fax]
      ,[CodiceFiscale]
      ,[PIVA]
      ,Null as [ice]
      ,[CodPagamento]
      ,[ancodval]
      ,[flgsconto]
      ,[CodIvaLDI]
      ,[NumeroLDI]
      ,[AnnoLDI]
      ,[pivastampafattura]
      ,[banca]
      ,[Email]
      ,[afflintr]
      ,[TipoNazione]
      ,[CodFilialePassiva]
      ,[SDI]
      ,[LegalMail]
      ,[FlgAssigne]
      ,[AgentAssigne]
      ,NULL AS [CodNazioneFiliale]
      ,NULL AS [flgbloccofatturazione] 
      ,NULL AS  [DateModif]
      ,NULL AS  [devise]
      ,NULL AS  [exo]
      ,NULL AS  [nexo]
      ,NULL AS [dexo]
      ,NULL AS [dendexo]
       FROM tmp.CLIENTICONTABILI
       WHERE codice NOT IN ('00001247','00001254','00001259')
       UNION 
       SELECT [CODFILIALE]
      ,[I_CODPRO]
      ,[CODICE]
      ,[RagioneSociale]
      ,[Indirizzo]
      ,[Cap]
      ,[Localita]
      ,[Provincia]
      ,[CodNazione]
      ,[DesNazione]
      ,[Telefono]
      ,[Fax]
      ,[CodiceFiscale]
      ,[PIVA]
      ,[ice]
      ,[CodPagamento]
      ,[ancodval]
      ,[flgsconto]
      ,[CodIvaLDI]
      ,[NumeroLDI]
      ,[AnnoLDI]
      ,[pivastampafattura]
      ,[banca]
      ,[Email]
      ,[afflintr]
      ,[TipoNazione]
       [CodFilialePassiva]
      ,NULL AS SDI
      ,NULL AS legalmail
      ,[FlgAssigne]
      ,[AgentAssigne]
     ,[CodNazioneFiliale]
     ,[flgbloccofatturazione]
     ,[DateModif]
     ,[devise]

     ,[exo]
     ,[nexo]
     ,[dexo]
      ,[dendexo] FROM tmp.CLIENTICONTABILIEXT;
GO
  

Msg 205,Niveau 16,État1,ProcédureGroupingCP,Ligne 5 [Ligne de   départdu lot 9]所有查询使用UNION,INTERSECT或   EXCEPT运算符中必须包含相等数量的表达式   目标列表。

2 个答案:

答案 0 :(得分:0)

选择的列数必须相等-在第一个选择中,有38列,而在第二个选择中,则有39列-这就是错误的原因

select col1, col2, col3, col4, ...coln from tablename1
union all
select col1, col2, col3, col4, ...coln from tablename2

答案 1 :(得分:0)

我检查您所有的参数是否等于两个表,可能是在将空值应用于列时(取决于另一个表)来设置数据类型。

例如:-

 CAST(NULL AS VARCHAR(100)) AS ICE