问题
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