SQL Server使用union创建视图

时间:2015-08-12 21:10:16

标签: sql-server

我需要创建一个视图,在查询中我使用union指令,但SQL Server显示有关此错误。

这是查询:

select 
    co.number, co.dateCo, co.value, 
    cl.id, cl.name, cl.lastname, 
    sl.id, sl.name, sl.lastname, 
    cd.id, cd.name, 
    d.lastname, '0000' CompanyID, '' CompanyName, 
from 
    contrat co 
inner join 
    customer cl on co.constumer = cl.id
inner join 
    Seller sl on co.seller = sl.id
inner join 
    collector cd on co.collector = cd.id

union

select 
    co.number, co.dateCo, co.value, 
    cl.id, cl.name, cl.lastname, 
    sl.id, sl.name, sl.lastname, 
    cd.id, cd.name, 
    d.lastname, cp.id CompanyID, cp.name CompanyName, 
from 
    contrat co 
inner join 
    customer cl on co.constumer = cl.id
inner join 
    Seller sl on co.seller = sl.id
inner join 
    collector cd on co.collector = cd.id
inner join 
    Company cp on co.company = co.id

1 个答案:

答案 0 :(得分:1)

您的from子句之前有额外的逗号。正确的陈述如下所示。

select co.number, co.dateCo, co.value, cl.id, cl.name, cl.lastname, sl.id,    
  sl.name, sl.lastname, cd.id, cd.name, d.lastname, '0000' CompanyID, '' 
  CompanyName 
from contrat co inner join customer cl on co.constumer=cl.id
inner join Seller sl on co.seller=sl.id
inner join collector cd on co.collector=cd.id
union
select co.number, co.dateCo, co.value, cl.id, cl.name, cl.lastname, sl.id, 
  sl.name, sl.lastname, cd.id, cd.name, d.lastname, cp.id CompanyID, cp.name 
  CompanyName 
from contrat co inner join customer cl on co.constumer=cl.id
inner join Seller sl on co.seller=sl.id
inner join collector cd on co.collector=cd.id
inner join Company cp on co.company=co.id