除了使用游标之外,还有什么方法可以将SELECT
结果用于后续的INSERT/UPDATE
查询吗?
类似的东西:
DECLARE @SELECTRESULT;
SELECT Something into @SELECTRESULT
FROM Somewhere
INSERT INTO SomewhereElse (X, XX, XXX)
SELECT Something, GETDATE(), 'XXX'
FROM @SELECTRESULT
UPDATE Somewhere
Set SomethingElse = 'ABC'
WHERE
Something in
(SELECT Something FROM @SELECTRESULT)
原因是我有来自多个表的相对复杂的查询,我不希望重复此代码,一次用于插入,第二次用于更新。
答案 0 :(得分:0)
您可以使用表变量。
像
这样的东西DECLARE @Table TABLE(
Col1 INT
)
INSERT INTO @Table
SELECT Col1
FROM Table
看看
答案 1 :(得分:0)
只需使用临时表就可以了:
将某些内容添加到#temporary_table FROM Somewhere WHERE blabla
答案 2 :(得分:0)
使用临时表。
CREATE TABLE #tempTable
(
Something int NOT NULL,
CurrentDate DateTime NULL,
XXX Varchar(50)
)
然后在多个表上使用复杂查询并将结果集插入tempTable。
Insert into #tempTable
-- Complex Select Query
确保所选查询返回的列按照#tempTable结构的顺序匹配。列数也应该匹配。 一旦你拥有了复杂数据的#tempTable,就可以多次使用它来进行插入和更新查询。
INSERT INTO SomewhereElse (X, XX, XXX)
SELECT * from #tempTable
UPDATE Somewhere
Set SomethingElse = 'ABC'
WHERE
Something in (SELECT Something FROM #tempTable)
答案 3 :(得分:0)
DECLARE @SELECTRESULT table(Something nvarchar(50)) --the data that you could reuse.
insert into @SELECTRESULT(Something)
SELECT Something
FROM Somewhere
INSERT INTO SomewhereElse (X, XX, XXX)
SELECT Something, GETDATE(), 'XXX'
FROM @SELECTRESULT
UPDATE Somewhere
Set SomethingElse = 'ABC'
WHERE Something in
(SELECT Something FROM @SELECTRESULT)