Create new table from query results

不羁的心 提交于 2019-12-13 02:41:42

问题


I am attempting to create a new table from the results a query. I've attempted select into, also have attempted create table.

I've attempted select into, also have attempted create table.

This is my original code, I am attempting to create a new table from the output of this code called '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)

I have attempted this but get this error, 'Incorrect syntax near '('.'

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));

回答1:


SQL Server 2014 does not support CTAS syntax. You could use SELECT ... INTO instead:

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)



回答2:


You should first Create your table then try to insert data into it. try something like this:

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)

make sure data type provided by your select statement is same as the table you will create.



来源:https://stackoverflow.com/questions/55973330/create-new-table-from-query-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!