Dynamic Select a Table With Ordered Column List (Code sample)



DECLARE @sql AS NVARCHAR(4000)=''
Declare @tablename nvarchar(50) ='MyTable'
Declare @schemaname nvarchar(50)='dbo'
 

SELECT  @sql= 'SELECT ' +(SELECT stuff( (SELECT ','+ QuoteName(COLUMN_NAME )  FROM  INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME =@tablename AND TABLE_SCHEMA =@schemaname  Order By COLUMN_NAME FOR XML PATH('')),1,1,'')) 
+ ' FROM '+  @schemaname+'.'+@tablename

--print @sql

exec(@sql)


Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s