Showing posts with label Table Variables. Show all posts
Showing posts with label Table Variables. Show all posts

Sunday, June 13, 2021

How to get list of column names from Table Variable @table

A table variable is a variable data type which can be used to store temporary data. It's defined using the DECLARE keyword and the table's structure is defined in the declaration as shown below:

declare @ns_source table
(
  col1_id int, 
  col2_name varchar(50),
  col3_desc varchar(50)
)    

Unlike temporary tables, table variables are not affected by a rollback. As regular variables, they keep the data which was modified during the transaction even if the transaction is rolled back.

Coming to get columns from table varaiable, here is how we can get using below query.

declare @ns_source table
(
  col1_id int, 
  col2_name varchar(50),
  col3_desc varchar(50)
)

select DP.N.value('local-name(.)', 'sysname') as ColumnName
from 
  (
  select NS.*
  from (select 1) as D(N)
    outer apply (
                select top(0) *
                from @ns_source
                ) as NS
  for xml path(''), elements xsinil, type
  ) as LV(X)
cross apply LV.X.nodes('*') as DP(N)

Result looks like below