这不是 sql server 的有效语法。您可以使用CREATE TABLE
并指定列名和类型来创建表,也可以执行SELECT INTO
包含数据的语句。
方法 1:创建表,然后填充:
CREATE TABLE SalesOrdersPerYear
( SalesPersonID int, BaseSalary float)
;
WITH Sales_CTE (SalesPersonID, BaseSalary)
AS
(
SELECT SALES_PERSON.SALES_PERSON_ID, SALES_PERSON.BASE_SALARY
FROM SALES_PERSON
WHERE SALES_PERSON_ID IS NOT NULL
)
insert into SalesOrdersPerYear
SELECT SalesPersonID, BaseSalary AS TotalSales
FROM Sales_CTE
ORDER BY SalesPersonID, BaseSalary;
方法 2 - 一步到位
WITH Sales_CTE (SalesPersonID, BaseSalary)
AS
(
SELECT SALES_PERSON.SALES_PERSON_ID, SALES_PERSON.BASE_SALARY
FROM SALES_PERSON
WHERE SALES_PERSON_ID IS NOT NULL
)
select SalesPersonID, BaseSalary AS TotalSales
into SalesOrdersPerYear
FROM Sales_CTE
ORDER BY SalesPersonID, BaseSalary;
当您需要指定有关表的更多信息(主键、索引、外键等)时,请使用方法 1。
对更临时的事情使用方法 2。(您通常会在此处使用临时表,例如 #SalesOrdersPerYear)。
无论哪种方式,数据现在都存储在您的表中,您可以再次使用它。
使用临时表:
-- Check for existence and drop first to avoid errors if it already exists.
if OBJECT_ID('tempdb..#SalesOrdersPerYear') is not null
drop table #SalesOrdersPerYear
WITH Sales_CTE (SalesPersonID, BaseSalary)
AS
(
SELECT SALES_PERSON.SALES_PERSON_ID, SALES_PERSON.BASE_SALARY
FROM SALES_PERSON
WHERE SALES_PERSON_ID IS NOT NULL
)
select SalesPersonID, BaseSalary AS TotalSales
into #SalesOrdersPerYear
FROM Sales_CTE
ORDER BY SalesPersonID, BaseSalary;
您还可以将其定义为表变量,这在方法之间有点交叉:
declare @SalesOrdersPerYear table
( SalesPersonID int, BaseSalary float)
;
WITH Sales_CTE (SalesPersonID, BaseSalary)
AS
(
SELECT SALES_PERSON.SALES_PERSON_ID, SALES_PERSON.BASE_SALARY
FROM SALES_PERSON
WHERE SALES_PERSON_ID IS NOT NULL
)
insert into @SalesOrdersPerYear
SELECT SalesPersonID, BaseSalary AS TotalSales
FROM Sales_CTE
ORDER BY SalesPersonID, BaseSalary;
此选项将仅在此批次中持续存在,并且不需要删除 - 就像任何其他变量一样。