我有一个从Excel电子表格导入的平面数据表....
tbl_ProductsImport
----------------------------------------------------------------------------------
ProductId | Name | Description | Attribute1 | Attribute2 | Attribute3 | Attribute4 etc...
----------------------------------------------------------------------------------
12345 P1 Some desc.. x x x
12346 P2 Some desc.. x
12347 P3 Some desc.. x x x x
12348 P4 Some desc.. x x
我想将其转换为下表结构......
tbl_Products
------------------------------
ProductId (pk) | Name | Description
tbl_Attributes
----------------------------------------------
AttributeId (pk) | Name (derrived from column)
tbl_ProductAttributes
----------------------
ProductId (fk) | AttributeId (fk)
所以我问,我怎么会写一个声明来做这个?
编辑:这将是计划数据导入作业的一部分,该作业在执行前截断所有现有数据。
答案 0 :(得分:1)
嗯。这会有用吗?令人讨厌的讨厌的动态SQL,但有时它必须完成。
INSERT tbl_Products
SELECT ProductId, Name, Description
FROM tbl_ProductsImport
INSERT tbl_Attributes (Name)
SELECT c.name
FROM sys.sysobjects o
JOIN sys.syscolumns c ON o.id = c.id
WHERE o.name = 'tbl_ProductsImport'
AND c.name LIKE 'Attribute%'
DECLARE @DynamicSQL VARCHAR(MAX)
SET @DynamicSQL = ''
DECLARE @AttributeId INT
DECLARE @AttributeName NVARCHAR(255)
SELECT @AttributeId = MIN(AttributeId)
FROM tbl_Attributes
WHILE (@AttributeId <= (SELECT MAX(AttributeId) FROM tbl_Attributes))
BEGIN
SELECT @AttributeName = Name
FROM dbo.tbl_Attributes
WHERE AttributeId = @AttributeId
SELECT @DynamicSQL =
'INSERT tbl_ProductAttributes
SELECT ProductId, ' + CONVERT(VARCHAR, @AttributeId) + '
FROM tbl_ProductsImport
WHERE ' + @AttributeName + ' = 1'
EXEC (@DynamicSQL)
SET @AttributeId = @AttributeId + 1
END
这假设tbl_ProductsImport中的Attributes值是BIT。没试过,所以可能是一个超级失败。
吉姆