T1 T2
id name id name
1 a 1 e
2 b 2 f
3 c 3 g
4 d 4 h
输出: -
T1 T2
id name id name
1 e 1 a
2 f 2 b
3 g 3 c
4 h 4 d
答案 0 :(得分:2)
不要交换从T1到T2的值,因为如果记录很大,那么交换数据需要更多时间,只需将表重命名为Follows
EXEC sp_rename 'T1', 'T1_10'
EXEC sp_rename 'T2', 'T1'
EXEC sp_rename 'T1_10', 'T2'
您可以在MSDN上找到有关此程序的文档。
如果需要包含模式名称,则只能包含在第一个参数中(也就是说,这不能用于将表从一个模式移动到另一个模式)。因此,例如,这是有效的:
EXEC sp_rename 'myschema.T1', 'T1_10'
更新:
作为OP表结构这里ID也需要重命名
sp_rename [PK_tblKeyTEST] ,[PK_tblKey]
感谢@ TT指点
答案 1 :(得分:0)
将t1复制到临时表
SELECT * INTO #swap FROM t1;
清空t1
DELETE FROM t1;
将t2复制到t1
INSERT INTO t1 SELECT * FROM t2;
清空t2
DELETE FROM t2;
将临时表复制到t2
INSERT INTO t2 SELECT * FROM #swap;
为了解决任何错误,请在事务中将其包装起来以确定。总而言之:
BEGIN TRY
BEGIN TRANSACTION;
SELECT * INTO #swap FROM t1;
DELETE FROM t1;
INSERT INTO t1 SELECT * FROM t2;
DELETE FROM t2;
INSERT INTO t2 SELECT * FROM #swap;
COMMIT TRANSACTION;
PRINT 'Success';
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
PRINT 'Fail';
END CATCH
答案 2 :(得分:0)
您也可以通过Inner Join
:
select t2.* from t1
inner join t2 on t2.id = t1.id ----- T1
select t1.* from t1
inner join t2 on t2.id = t1.id ----- T2
结果:
T1 T2
id name id name
1 e 1 a
2 f 2 b
3 g 3 c
4 h 4 d