简体   繁体   中英

SQL Server - Column Name as Variable

I'm just wondering if this is possible, I am trying to update/insert into columns however I would like to be able to select the column name into a variable and do it like so:

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
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)

Why do you want to do this?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM