SQL Server table field value to column name example

Source: Internet
Author: User
A few days ago, my colleague asked me how to convert a field value to a column. I wrote a simple Demo to share it. The Code is as follows: -- create a test table and add Test Data createtable # temp (amoney, bvarchar (10) * insertinto # temp (a, B) values () insert

A few days ago, a colleague asked me how to convert a field value to a column. I wrote a simple Demo to share it. The Code is as follows: -- create a test table and add Test Data create table # temp (a money, B varchar (10)/* insert into # temp (a, B) values (10, '1') insert

SQL Server table field value to column name example

A few days ago, my colleague asked me how to convert the field value into a field column and wrote a simple Demo to share it.

The Code is as follows:

-- Create a test table and add Test Data
Create table # temp (a money, B varchar (10 ))

/*
Insert into # temp (a, B) values (10, '1 ')
Insert into # temp (a, B) values (20, '2 point ')
Insert into # temp (a, B) values (20, '3 ')
Insert into # temp (a, B) values (20, '4 point ')
Insert into # temp (a, B) values (20, '5 ')
Insert into # temp (a, B) values (30, '6 point ')
Insert into # temp (a, B) values (20, '7 point ')
Insert into # temp (a, B) values (48, '8 point ')
Insert into # temp (a, B) values (20, '9 point ')
Insert into # temp (a, B) values (15, '10 ')
*/
Select * from # temp

-- Query Result
Declare @ SQL nvarchar (max) = '';
Select @ SQL = @ SQL + (case @ SQL when ''then'' 'else', 'end) + 'max (case B when''' + B + ''' then a else 0 end) ['+ B +'] 'from # temp;
Set @ SQL = 'select' + @ SQL + 'from # temp ;';
Exec sp_executesql @ SQL;

-- Drop table # temp

Posted on

,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.