按列索引进行SQL更新

时间:2013-12-24 20:47:37

标签: sql sql-server

我正在使用SQL Server,我有Products表和列ProductID, ProductName, ProductSalePrice, ProductBuyPrice(还有更多列tbh。)

通常您可以像这样更新数据库:

Update Products 
Set ProductSalePrice = 54 
where ProductID = 12947

但我想要的是,使用带有列索引的update命令而不是列名。像这样:

Update Products 
Set "Third Column" = 54 
where ProductID = 12947

如何按列索引更新表?有什么建议吗?

编辑:看起来SQL Server没有自然的列顺序供查询使用。我错误地猜到了我的做法。我希望有一个选项,就像上面的代码一样,但没有在数据库上工作。

编辑2:我已经接受了以下答案,因为没有数据库工作似乎无法做到。如果有新的方法,我可能会改变接受的答案。感谢。

2 个答案:

答案 0 :(得分:3)

如果确实需要此功能,您可以使用INFORMATION_SCHEMA表来查找列及其顺序(使用ORDINAL_POSITION)。然后使用update语句构建动态查询。

declare @columnNum int
SET @columnNum = 3

declare @column nvarchar(100)

set @column = 
(
    SELECT TOP 1
        COLUMN_NAME
    from INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'Products'
        AND ORDINAL_POSITION = @columnNum
)

declare @sql nvarchar(500)

set @sql = 'Update Products Set ' + @column + ' = 54 where ProductID = 12947'

sp_executesql @sql

答案 1 :(得分:0)

在字符串变量中构建查询,然后执行它(more on EXECUTE @variable):

declare @update as varchar(max) = 'update Products set Column' + @columnNumber + '= .....'
exec @update

需要这是一个提示,你最好重新设计你的数据库,但我知道这并不总是可行。

相关问题