How to get column names in the row wise along with their values

  • Screenshot_2020-05-11-22-52-24-130_com.android.chrome

  • google for unpivot - or use a outer apply selecting each column and its value with a case statement and a group by

     

    when you have some code showing what you have tried (after you search the above) get back to us if you are still stuck.

  • Select custid,Field name,RowValue
    From TblEmails as a
    Unpivot
    (
    Rowvlaue for fieldName in (select fieldName from #column_names)
    ) As unpiv
    Order by field name
  • I am not able to use a select query after in statement . Could you please help me out on this

  • nearly there as not too hard to put a sample code was it?

    unpivot has one small issue - the columns need to be hardcoded (or dynamic SQL used) and they must all be the same datatype and size

    if you need dynamic number of columns you should google for "sql server unpivot dynamic column list" to get some examples

    so on this case all those 3 fields must be converted to a varchar with a size equal to the lastest one

    with tblemails as
    (select 'cust-1' as custid
    , convert(varchar(30), 'first name') as FirstName
    , convert(varchar(30), 'last nane') as LastName
    , convert(varchar(30), 'email@email.com') as Email
    )
    Select custid,fieldname,RowValue
    From TblEmails as a
    Unpivot
    (
    RowValue for fieldName in (FirstName, LastName, Email)
    ) As unpiv
    Order by fieldname

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply