How to make a query with dynamic column in sql server 2012 -
i have sample code below. result such takes these columns varchar type.
declare @col1 varchar(80)='[column1]' declare @col2 varchar(80)='[column2]' select @col1,@col2 mytable
you have use dynamic sql:
declare @col1 varchar(80) = 'column1'; declare @col2 varchar(80) = 'column2'; declare @sql nvarchar(max); select @sql = 'select ' + quotename(@col1) + ', ' + quotename(@col2) + ' mytable;'; exec sp_executesql @sql;
note have make sure column names real column names. need parameterize query added security. if of these wrong, may create huge security problems.
Comments
Post a Comment