使用动态SQL更新表

时间:2016-08-04 11:21:38

标签: sql sql-server dynamic-sql

在下表中," ColumnDifference":

Screenshot of table

" ColumnName"中的每个单元格是另一个表中列的名称," regressionDifferences"。我必须从regressionDifferences中选择ColumnName中列出的每个列,在UniqueID上匹配,并将每个字符串中的前八个字符插入ColumnContent。

到目前为止,我有:

DECLARE @LoopCounter INT = 1, @MaxRowNumber INT = 420,
@ColumnName VARCHAR(max), @UniqueID VARCHAR(max), @ColumnContent VARCHAR(max), @SQL VARCHAR(max), @table VARCHAR(max)

WHILE(@LoopCounter < @MaxRowNumber)
BEGIN
SELECT @ColumnName = ColumnName
FROM ColumnDifference WHERE RowNumber = @LoopCounter

SELECT @ColumnContent = ColumnContent
FROM ColumnDifference WHERE RowNumber = @LoopCounter

SELECT @UniqueID = UniqueID
FROM ColumnDifference WHERE RowNumber = @LoopCounter

SET @sql = 'UPDATE ColumnDifference
SET ' + @ColumnContent + ' = (SELECT DISTINCT SUBSTRING(' + @ColumnName + ',0,9) FROM regressionDifferences rD 
WHERE rD.UniqueID LIKE '''
                  + @UniqueID + '%'')'

exec(@sql);

SET @LoopCounter = @LoopCounter + 1

END

如果我将@sql设置为:

'SELECT DISTINCT SUBSTRING(' + @ColumnName + ',0,9) FROM regressionDifferences rD WHERE rD.UniqueID LIKE ''' + @UniqueID + '%'''

我得到了正确的结果,但都在不同的表中:

Screenshot of SELECT

如果我打印原始的@sql,我会得到一个空白的消息框。

执行时,我得到&#34;命令已成功完成&#34;但在ColumnDifference中没有任何变化。任何帮助将不胜感激!

由于

2 个答案:

答案 0 :(得分:0)

如果这可以为​​您提供所需的结果,则可以编写更新:

DECLARE @LoopCounter INT = 1 , @total as  int , @colname as varchar(10) , @sql as nvarchar(1000)

--- getting the max no of rows
set @total =(select count(*) from 
(select cd.ColumnName, row_number ()over(order by rd.UniqueID) as rw  from regressionDifferences rd
inner join ColumnDifference cd on rd.UniqueID = cd.UniqueID)t)


WHILE(@LoopCounter < @total)
BEGIN

--- select one row at a time
set @colname = (select t.ColumnName from (select cd.ColumnName, row_number ()over(order by rd.UniqueID) as rw  from regressionDifferences rd
inner join ColumnDifference cd on rd.UniqueID = cd.UniqueID)t
where t.rw=@LoopCounter)


SET @sql = 'SELECT SUBSTRING(' + @colname + ',0,9) FROM regressionDifferences rD'

exec(@sql);

SET @LoopCounter = @LoopCounter + 1

END

答案 1 :(得分:0)

.normaltag { color: red; }出现问题。看看它应该如何。这应该有效:

SET ' + @ColumnContent'

我还修复了初始选择:您根本不需要提取DECLARE @LoopCounter INT = 1, @MaxRowNumber INT = 420, @ColumnName VARCHAR(max), @UniqueID VARCHAR(max), @SQL VARCHAR(max), @table VARCHAR(max); WHILE(@LoopCounter < @MaxRowNumber) BEGIN SELECT @ColumnName = ColumnName , @UniqueID = UniqueID FROM ColumnDifference WHERE RowNumber = @LoopCounter; SET @sql = 'UPDATE ColumnDifference SET ColumnContent = (SELECT DISTINCT SUBSTRING(' + @ColumnName + ',0,9) FROM regressionDifferences rD WHERE rD.UniqueID = ''' + @UniqueID + ''')'; PRINT @sql; exec(@sql); SET @LoopCounter += 1; END (或者是吗?)。
我带走了@ColumnContent:有LIKE,它必须是唯一的,不喜欢。
其他一些小变化。