我有一个具有唯一 ID 的表 Items:itemId,... 行示例:‘3506’,...
我有一个包含以下列的 ItemProperties 表: itemId、创建日期、修改日期、属性 1、属性 2、属性 3、属性 4、属性 5
行示例:‘3506’、‘2012…’、‘2012…’、‘prop1’、‘prop2’、‘prop3’、‘prop4’、‘prop5’
我需要将 ItemProperties 表的每一行拆分为 NewItemProperties 表中的 5 个单独的行,其中包含以下列: itemId、创建日期、修改日期、属性编号、属性
5 行示例:
‘3506’, ‘2012…’, ‘2012…’, 1, ‘prop1’
‘3506’, ‘2012…’, ‘2012…’, 2, ‘prop2’
‘3506’, ‘2012…’, ‘2012…’, 3, ‘prop3’
‘3506’, ‘2012…’, ‘2012…’, 4, ‘prop4’
‘3506’, ‘2012…’, ‘2012…’, 5, ‘prop5’
限制: - 不应处理具有不再位于 Items 表中的 itemId 的 ItemProperties
此过程不应覆盖/更新 NewItems 表中已有的项目(id =id 且 propertynumber=property1~5 列的编号)
微软 SQL Server 2008 R2
ItemProperties 表中约有 800000 行
我现在的解决方案非常慢:
...
DECLARE c CURSOR read_only FOR SELECT * from ItemProperties
DECLARE @ID varchar(14), @CREA datetime, …
OPEN c
FETCH NEXT FROM c INTO @ID, @CREA, @MODI, @COL, @SIZE, @PAT, @YEAR, @ITEM
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN
select * from Items where itemId = @ID
if @@ROWCOUNT = 0
BEGIN
GOTO Fetch_Next
END
select * from ItemProperties where itemId = @ID AND propertynumber = 1
if @@ROWCOUNT = 0
INSERT INTO NewItemProperties
VALUES(@ID, '1', @COL, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
select * from ItemProperties where itemId = @ID AND propertynumber = 2
if @@ROWCOUNT = 0
INSERT INTO NewItemProperties
VALUES(@ID, '2', @SIZE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
…
END
Fetch_Next:
FETCH NEXT FROM c INTO @ID, @CREA, @MODI, @COL, @SIZE, @PAT, @YEAR, @ITEM
...
我可以通过删除创建和修改日期来优化我的获取语句,但这就是我能想到的全部。我无法将其放入逆透视查询中。基本上任何比光标更快的东西都会帮助我。欢迎所有想法。谢谢。
最佳答案
试试这个
INSERT INTO NewItemProperties
SELECT itemId, '1', property1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
FROM ItemProperties
UNION ALL
SELECT itemId, '2', property2, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
FROM ItemProperties
......
UNION ALL
SELECT itemId, '5', property5, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
FROM ItemProperties
关于sql - 将一个表的 5 列保存到另一个表中的 5 行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13920968/