简体   繁体   中英

how to change dynamically column name in sql

i have to change column name dynamically in loop in sql, using concat to add string and dynamic column name and getting error-'The definition for column 'CONCAT' must include a data type.'

this is my code-

SELECT @SOURCENAME='['+SOURCE_NAME+']' FROM #temptable2 WHERE  [id] = @StartRow;
                                                    SET @SQL='ALTER TABLE #TmpWcompData ADD '+@SOURCENAME+' float'
SET @SQL1='ALTER TABLE #TmpWcompData ADD concat(mae,'+@SOURCENAME+') float'
                                
                                
EXECUTE SP_EXECUTESQL @SQL,@SQL1;

CONCAT can't be used in ALTER TABLE . You can fix it as the following:

SET @SQL1 = 'UPDATE #TmpWcompData SET ' + @SOURCENAME + ' = CONCAT(mae, ' + @SOURCENAME + ')';

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