在我的数据库中,我有一些非规范化的表和一个将正常数据发送到过程的程序。我的表的一些例子是这样的:
非正规表:
------------------------------------------------------------------------------------------
|Id |Description| date | UserId1 | Percent1 | Desc1 | ... | UserId10 | Percent10 | Desc10|
------------------------------------------------------------------------------------------
| 0 | row 1 | 2014 | 10 | 10% | | ... | 1 | 30% | |
| 1 | row 2 | 2012 | 5 | 4% | | ... | 7 | 47% | |
| 2 | row 3 | 2015 | 20 | 30% | | ... | 25 | 33% | |
------------------------------------------------------------------------------------------
和我的程序中的普通表如:
---------------------------
| UserId | Percent | Desc |
---------------------------
| 70 | 20 | |
| 30 | 7 | |
---------------------------
注意:
现在我应该:
我该怎么做?
答案 0 :(得分:0)
最后,我可以通过创建命令字符串来解决我的问题并执行它。
DECLARE @ColNames nvarchar(max) = '[Description], [Date]'
DECLARE @Values nvarchar(max) = CAST(@Description AS NVARCHAR(10)) + ', ' +
'CAST(''' + CAST(GETDATE() AS NVARCHAR(50)) + ''' AS DATETIME), '
DECLARE @UserId BIGINT
DECLARE @Percent FLOAT
DECLARE @Desc nvarchar(300)
DECLARE @i INT = 1
DECLARE cur CURSOR FOR SELECT [UserId], [Percent], [Desc] FROM Table2
OPEN cur
FETCH NEXT FROM cur INTO @UserId, @Percent, @Desc
WHILE @@FETCH_STATUS = 0 AND @i <= 10
BEGIN
SET @ColNames += ', UserId' + CAST(@i AS NVARCHAR(3)) +
', Percent' + CAST(@i AS NVARCHAR(3)) +
', Desc' + CAST(@i AS NVARCHAR(3))
SET @Values += CAST(@UserId AS NVARCHAR(20)) + ', ' +
CAST(@Percent AS NVARCHAR(20)) + ', ' +
'N''' + @Desc + ''', '
FETCH NEXT FROM cur INTO @UserId, @Percent, @Desc
SET @i += 1
END
CLOSE cur
DEALLOCATE cur
SET @Values = SUBSTRING(@Values, 1, LEN(@Values) - 1)
DECLARE @Command nvarchar(max) =
'INSERT INTO Table1' +
' ( ' + @ColNames + ')' +
' VALUES ( ' + @Values + ')'
EXEC sp_executesql @Command
这项工作很棒,更新程序使用这个概念,但我不了解使用这个概念的性能和劣势。