三个 CTE 问题

发布于 2024-12-03 18:00:05 字数 481 浏览 1 评论 0原文

我希望做这样的事情:

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

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

还有两个问题:

  1. 有没有办法构造一个空的CTE?
  2. CTE 可以修改吗?我可以在构建后插入行吗?

更新 我找到了主要问题的答案,目的是用任意数据填充 CTE:

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

I was hoping to do something like this:

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

In short, I was hoping the output would simply become the CTE input. Is there a way to fix this?

Two more questions:

  1. Is there a way to construct an empty CTE?
  2. Can a CTE be modified? Can I insert rows after it has been constructed?

UPDATE
I found the answer to my primary question, with the intent of filling a CTE with arbitrary data:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

琉璃繁缕 2024-12-10 18:00:05

另外两个问题

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

the two other questions

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文