是否可以进行动态声明?我将解释:我有一张桌子COLUMNAMES
:
ID|Name
1|Country
2|City
3|District
4|Neighbourhood
对于该表中的每条记录,我想做类似的事情:
declare @i int = 1
declare @number int
set @number = (SELECT count(*) FROM COLUMNNAMES)
While @i <= @number
BEGIN
Execute ('Declare column' + @i +'varchar(25)')
Execute ('set column' + @i +' = (Select NAME from COLUMNAMES where id = ' + @i)
set @i = @i + 1
END
这个想法是我得到一个变量列表(字符串),我可以用它来创建带有动态表别名的 SELECT 语句:
Execute ('Select SOMECOLUMN as ' + @columname + @i +', ANOTHERCOLUMN as ' + @columname + @i +', ATHIRDCOLUMN as ' + @columname + @i + ' FROM SOMETABLE')
这可以做到吗?如果是这样,怎么做?