My goal is to select result from one CTE and insert into other table with another CTE in the same procedure. How to do it?
My error is...
invalid object name xy.
My query is
WITH ds
(
Select a, b, c
from test1
),
xy
(
select d, e, f
from test2
where (uses conditions from ds)
)
Select *
from ds (the result set of ds, am exporting this to csv)
Insert into AuditTest
(
Select * from xy
)
The CASE statement is SQL's way of handling if/then logic. The CASE statement is followed by at least one pair of WHEN and THEN statements—SQL's equivalent of IF/THEN in Excel. Because of this pairing, you might be tempted to call this SQL CASE WHEN , but CASE is the accepted term.
The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query.
The plus sign is Oracle syntax for an outer join. There isn't a minus operator for joins. An outer join means return all rows from one table. Also return the rows from the outer joined where there's a match on the join key.
%s is a placeholder used in functions like sprintf. Check the manual for other possible placeholders. $sql = sprintf($sql, "Test"); This would replace %s with the string "Test".
A CTE is only good for one query, but it looks like you can use a CTE in each query:
WITH ds AS
(
Select a, b, c from test1
)
Select * from ds (the result set of ds, am exporting this to csv)
WITH xy AS
(
select d,e,f from test2 where (uses conditions from test1)
)
Insert into AuditTest
(
Select * from xy
)
You actually can do both the insert and output the results using the OUTPUT clause to return the inserted rows.
;WITH ds AS
(
Select a, b, c from test1
),
xy AS
(
select d, e, f from test2 where (uses conditions from ds)
)
Insert into AuditTest
output inserted.d, inserted.e, inserted.f
Select d, e, f from xy
or a real test
CREATE TABLE #Test (a int)
;WITH ds AS
(
Select 0 as a, 1 as b, 2 as c
),
xy AS
(
select a as d, b as e from ds
)
Insert into #Test
OUTPUT inserted.a
Select e from xy
You can run the INSERT
thusly, you can't run multiple queries after your cte
:
;WITH ds AS ( Select a, b, c
from test1
)
,xy AS ( select d,e,f
from test2
where (uses conditions from test1)
)
Insert into AuditTest
Select *
from xy
In this situation using temporary tables may be beneficial since you'll be re-running a query multiple times otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With