根据查询结果创建新表

时间:2019-05-03 15:53:05

标签: sql left-join sql-server-2014

我正在尝试根据查询结果创建一个新表。我尝试过 选择进入,也尝试创建表。

我尝试过 选择进入,也尝试创建表。

这是我的原始代码,我试图从此代码的输出中创建一个名为'InitialJoinwithCPCL'的新表

select *
from [dbo].[Combined] as a
left join [dbo].[CPCL] as b
    on a.[StateAbbr] = b.[ST] and a.[CropName] = b.[CROPNAME]
where cropyear <> 2019 and (policynumber is not null) 
and (PolicyAcres <> 0) and (Policyliability <> 0 or PolicyAcres <= 0) and (Endorsement is null)

我已经尝试过此操作,但收到此错误,“((。)附近的语法不正确。”

create table InitialJoinwithCPCL
as (select * 
from [dbo].[Combined] as a
left join [dbo].[CPCL] as b
    on a.[StateAbbr] = b.[ST] and a.[CropName] = b.[CROPNAME]
where cropyear <> 2019 and (policynumber is not null) 
and (PolicyAcres <> 0) and (Policyliability <> 0 or PolicyAcres <= 0) and (Endorsement is null));

2 个答案:

答案 0 :(得分:1)

SQL Server 2014不支持CTAS syntax。您可以改用SELECT ... INTO

select *   -- * is antipattern and columns should be explicitly listed
into InitialJoinwithCPCL
from [dbo].[Combined] as a
left join [dbo].[CPCL] as b
    on a.[StateAbbr] = b.[ST] and a.[CropName] = b.[CROPNAME]
where cropyear <> 2019 and (policynumber is not null) 
and (PolicyAcres <> 0) and (Policyliability <> 0 or PolicyAcres <= 0) and (Endorsement is null)

答案 1 :(得分:0)

您应该首先创建表,然后尝试在表中插入数据。尝试这样的事情:

CREATE TABLE InitialJoinwithCPCL ( [Id] bigint, [Name] nvarchar(max), .... )
INSERT INTO InitialJoinwithCPCL
SELECT * 
FROM [dbo].[Combined] as a
LEFT JOIN [dbo].[CPCL] as b
on a.[StateAbbr] = b.[ST] and a.[CropName] = b.[CROPNAME]
WHERE cropyear <> 2019 and (policynumber is not null) 
AND (PolicyAcres <> 0) and (Policyliability <> 0 or PolicyAcres <= 0) AND 
(Endorsement is null)

确保您的select语句提供的数据类型与要创建的表相同。