更新列名称未知的表

时间:2011-08-02 07:31:25

标签: sql sql-server tsql

我有一张桌子,但我不知道它的列(我只知道它有“id(Uniqueidentifier)列”)。

我可以使用以下查询获取表中的所有列:

    DECLARE @columnNames NVARCHAR(4000) = ''

    SELECT @columnNames += '[' + COLUMN_NAME + '] '
    FROM INFORMATION_SCHEMA.Columns
    WHERE TABLE_NAME = 'MY_TABLE' AND COLUMN_NAME NOT IN ('id')
    ORDER BY COLUMN_NAME

现在我想用另一条记录的数据更新一条记录......

我该怎么做?

谢谢大家......

2 个答案:

答案 0 :(得分:1)

这是你如何构建动态sql

DECLARE @columnNames NVARCHAR(4000) 
DECLARE @idfrom int, @idto int
DECLARE @table nvarchar(50)
SET @table = 'MY_TABLE'
SET @idfrom = 5 -- id you are copying from
SET @idto = 2   -- id you are copying to

DECLARE @sqlstring nvarchar(max)

SELECT @columnNames = coalesce(@columnNames, 'SET ') + '[' + COLUMN_NAME + ']=t2.' + '[' + COLUMN_NAME + '],'
FROM INFORMATION_SCHEMA.Columns 
WHERE TABLE_NAME = @table AND COLUMN_NAME NOT IN ('id') 
ORDER BY COLUMN_NAME 

SET @sqlstring = 'update t1 ' +stuff(@columnNames, len(@columnNames),1,'') + ' 
FROM @t t1
join @t t2 on t1.id =' + cast(@idto as varchar) + '
and t2.id = ' + cast(@idfrom as varchar)

EXEC( @sqlstring )

答案 1 :(得分:0)

我认为你可以创建一个“insert into table1 ... select ... from table2”type insert string,然后用sp_executesql执行它。

DECLARE @insertColumnNames NVARCHAR(4000) = ''
DECLARE @selectColumnNames NVARCHAR(4000) = ''

SELECT @insertcolumnNames += ',' + '[' + COLUMN_NAME + '] '
FROM INFORMATION_SCHEMA.Columns
WHERE TABLE_NAME = 'TABLE_1' AND COLUMN_NAME NOT IN ('id')
ORDER BY COLUMN_NAME

SELECT @selectcolumnNames += ',' + '[' + COLUMN_NAME + '] '
FROM INFORMATION_SCHEMA.Columns
WHERE TABLE_NAME = 'TABLE_2' AND COLUMN_NAME NOT IN ('id')
ORDER BY COLUMN_NAME

sp_executesql ('insert into TABLE_1 ('+@insertcolumnNames+') select '+ @selectcolumnNames +' from TABLE_2');

我认为类似的东西可以起作用 (你需要从列字符串中删除额外的内容,而这根本没有经过测试,只是一个想法)