SQL 插入临时表而不指定值?
我有一个当前使用一个 CTE 的存储过程。这个工作原理如下:
WITH MY_CTE AS
(
// Logic here uses SELECT * from a single table.
)
SELECT *
INTO #Tasks
FROM MY_CTE;
我现在需要选择调用另一个 CTE,它将向原始临时表添加更多数据。我希望做这样的事情:
IF @Option = 1
BEGIN
INSERT INTO #Tasks
(
WITH MY_OTHER_CTE
(
// Logic here uses SELECT * from same table as first CTE.
)
SELECT *
FROM MY_OTHER_CTE
)
END
问题是 INSERT INTO #Tasks 调用需要指定 VALUES 列。两个 CTE 都从同一个表返回记录。原始存储过程的好处是,即使该表中的列发生更改,它也可以工作,因为我使用的是 SELECT *
。我可以指定列,知道它们在共享表中的内容,但我失去了这个好处(在这种特定情况下这是一个非常有用的好处)。有没有一种方法可以完成我想要做的事情,知道它们都从同一个表中进行选择并且列将始终匹配?
I have a stored procedure that currently uses one CTE. This one works like so:
WITH MY_CTE AS
(
// Logic here uses SELECT * from a single table.
)
SELECT *
INTO #Tasks
FROM MY_CTE;
I now have a requirement to optionally call another CTE that will add more data to the original temp table. I was hoping to do something like this:
IF @Option = 1
BEGIN
INSERT INTO #Tasks
(
WITH MY_OTHER_CTE
(
// Logic here uses SELECT * from same table as first CTE.
)
SELECT *
FROM MY_OTHER_CTE
)
END
The problem is that the INSERT INTO #Tasks
call requires specifying VALUES
columns. Both CTE's return records from the same table. The good benefit of original stored procedure was that it would work even if columns in that table changed, since I was using SELECT *
. I could specify the columns knowing what they are in the shared table, but I lose that benefit (which in this specific case is an extremely useful benefit). Is there a way to accomplish what I'm trying to do, knowing that they are both selecting from the same table and that the columns will always match?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这有效吗?
如果您从中选择的表(以及临时表)具有标识列,您可能会遇到另一个挑战
Does this work?
You might have another challenge if the table you're selecting from (and hence the temp table) has an identity column
我将从强制性的“出于 6,354 个原因列出您的专栏是一个很好的做法”开始。但我们都经历过你无法做到的地方;-)
无论如何,我解决这个问题的方法是使用派生表和派生表。工会。这里的关键是执行一系列 UNION 并使用 WHERE 标准来删除您不想运行的查询。显然,所有表都需要以相同的顺序具有相同的数据类型才能工作,但代码可能看起来像......
编辑
我想我忽略了你的“两个 CTE”请求,但我怀疑这会让你到达同一个地方。
I'll start with the obligatory "listing your columns out is good practice for 6,354 reasons." But we've all been there where you can't ;-)
Anyway, the way I would tackle this is with derived tables & Unions. The key here is doing a series of UNION's and using your WHERE criteria to drop out the queries you don't want to run. Obviously all tables need to have the same datatypes in the same order for this to work, but the code could look something like....
EDIT
I guess I ignored your "two CTE's" request, but I suspect this will get you to the same place.