我想在MS SQL中实现一个在Oracles PL / SQL中看起来像这样的构造:
declare
asdf number;
begin
for r in (select * from xyz) loop
insert into abc (column1, column2, column3)
values (r.asdf, r.vcxvc, r.dffgdfg) returning id into asdf;
update xyz set column10 = asdf where ID = r.ID;
end loop;
end;
任何想法如何实现这一点都会有所帮助。
提前致谢
答案 0 :(得分:6)
这似乎只是一张桌子的副本,对吧?
好:
SELECT column1, column2, column3 INTO abc FROM xyz
我认为你也可以像
那样INSERT INTO abc SELECT column1, column2, column3 FROM xyz
但在第二种情况下你需要先创建表,第一种情况也是创建表
干杯 约翰内斯
答案 1 :(得分:3)
没有光标但带有临时列的版本:
-- //temporarily add the column (assume the table "abc" already exists)
ALTER TABLE "abc" ADD xyzID INT;
GO;
-- //insert all the data (assuming the ID field on "xyz" is called ID)
INSERT INTO "abc" (column1, column2, column3, xyzID) SELECT asdf, vcxvc, rdffgdfg, ID FROM "xyz";
-- //update "xyd" with the new ID
UPDATE "xyd" SET column10 = "abc".ID FROM "xyd" INNER JOIN "abc" ON "xyd".ID = "abc".xydID
-- //drop the temporary column
ALTER TABLE "abc" DROP COLUMN xyzID;
答案 2 :(得分:2)
declare @asdf int/varchar -- unsure of datatype
declare @vcxvcint/varchar -- unsure of datatype
declare @dffgdfg int/varchar -- unsure of datatype
declare @id int
declare db_cursor CURSOR FOR SELECT asdf, vcxvc, dffgdfg FROM xyz
OPEN db_cursor
FETCH NEXT FROM db_cursor
INTO @asdf, @vcxvcint, @dffgdfg
WHILE @@FETCH_STATUS = 0
BEGIN
insert into abc (column1, column2, column3) values (@asdf, @vcxvcint, @vcxvcint)
set @id = scope_identity() -- This will get the auto generated ID of the last inserted row
update xyz set column10 = @asdf where id = @
FETCH NEXT FROM db_cursor INTO @name
END
CLOSE db_cursor
DEALLOCATE db_cursor
当然,如果您尝试将光标隐藏到生产代码中,基本上所有DBA都会杀了你。
答案 3 :(得分:1)
如果我理解你的要求(我不熟悉PL / SQL),看起来很简单:
INSERT INTO abc(column1, column2, column3) SELECT asdf, vcxvc, dffgdfg FROM xyz;
UPDATE xyz SET column10 = id;
但我只是猜测你的意图,希望没有被误解。
P.S。:已经指出,你必须已经创建了表abc
答案 4 :(得分:0)
希望这就是你要找的东西:
declare
asdf number;
begin
for r in (select * from xyz) loop
insert into abc (column1, column2, column3)
values (r.asdf, r.vcxvc, r.dffgdfg) returning id into asdf;
update xyz set column10 = asdf where ID = r.ID;
end loop;
end;
将成为
DECLARE @asdf int
DECLARE @ID int
DECLARE @MyTmpTableVar table(asdf int, abc_id int)
// insert records from your cursor r into table abc,
// and return a temporary table with "id" and "asdf" fields from the xyz table
INSERT INTO abc(column1, column2, column3)
OUTPUT asdf, id INTO @MyTmpTableVar
SELECT r.asdf, r.vcxvc, r.dffgdfg
FROM xyz
// if it would return just one row and you wanted to find the value
//SELECT @asdf = asdf, @id = abc_id
//FROM @MyTmpTableVar
// update the table xyz with the values stored in temporary table
// restricting by the key "id"
UPDATE xyz
SET xyz.column10 = t.asdf
FROM @MyTmpTableVar AS t
WHERE xyz.id = t.abc_id
Oracle中返回子句的sqlServer版本是 OUTPUT 子句。
请访问 this msdn page 获取完整信息