SQL Server - 列名作为变量

时间:2015-02-09 13:01:31

标签: sql tsql insert sql-server-2012

我只是想知道这是否可行,我正在尝试更新/插入列但是我希望能够将列名称选择为变量并按照这样做:

DECLARE @Col
SET @Col = (SELECT TOP 1 somecolumnname FROM mytable)

INSERT INTO someothertable
(ID, @Col) --This is the part I'm querying
SELECT 
ID, 
SomeData
FROM yetanothertable

2 个答案:

答案 0 :(得分:3)

DECLARE @Col as Varchar(100)
SET @Col = (SELECT TOP 1 somecolumnname FROM mytable)

DECLARE @SQL AS VARCHAR(500)
SET @SQL = 'INSERT INTO someothertable'
SET @SQL = @SQL + '(ID,' + @Col + ')'
SET @SQL= @SQL + ' SELECT ID, SomeData FROM yetanothertable'

EXEC(@SQL)

答案 1 :(得分:2)

你为什么要这样做?

DECLARE @Col varchar(100), @SQL varchar(1000)
SET @Col = (SELECT TOP 1 somecolumnname FROM mytable)

set @SQL='
INSERT INTO someothertable
(ID, '+@Col+')
SELECT 
ID, 
SomeData
FROM yetanothertable'
EXEC(@SQL)