How to create a table using "With" clause in SQL
This is not valid syntax for sql server. you can either create a table using CREATE TABLE
and specifying the column names and types, or you can do a SELECT INTO
statement including data.
Approach 1 : Create the table and then populate:
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;
Approach 2 - all in one step
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;
Use approach 1 when you need to specify more about the table (primary keys, indexes, foregin keys etc.
Use approach 2 for things that are more temporary. (you would normally use a temporary table such as #SalesOrdersPerYear here).
Either way, the data is now stored in your table, and you can use it again.
Using temporary tables:
-- 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;
You could also define it as a table variable, which is a bit of a cross between the approaches:
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;
This option will only persist with this batch, and does not need dropping - just like any other variable.