三个CTE问题

时间:2011-09-10 01:34:34

标签: sql-server tsql common-table-expression

我希望能做到这样的事情:

WITH Hello (Name)
AS (
INSERT INTO MyTest
OUTPUT 
  inserted.Name
VALUES ('George')
)
SELECT * FROM Hello

简而言之,我希望输出只会成为CTE输入。有办法解决这个问题吗?

还有两个问题:

  1. 有没有办法构建一个空的CTE?
  2. 可以修改CTE吗?我可以在构造后插入行吗?
  3. 更新 我找到了我的主要问题的答案,目的是用任意数据填充CTE:

    ;WITH stuff AS (
      SELECT * FROM ( VALUES
       (123, 1),
       (234, 1),
       (345, 0)
      ) [X](id, pref)
    )
    SELECT * FROM stuff
    

1 个答案:

答案 0 :(得分:2)

另外两个问题

1)

WITH Hello 
AS (
select  name
from sysobjects where 1 =0
)
SELECT * FROM Hello --no rows

2)

-- ***  update  ***

create table testNow(id int)
insert testNow values(1)

;WITH Hello 
AS (select id from testNow)

update Hello set id = 2 -- update cte

SELECT * FROM testNow --table now has value 2

-- ***  insert   ***

;WITH Hello 
AS (
select id from testNow

)

insert Hello values( 3 )

SELECT * FROM testNow --table now has 2 rows