Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Columns into rows with their respective data in sql server

I have a scenario where I need to convert columns of table to rows eg - table - stocks:

ScripName       ScripCode       Price   
-----------------------------------------
20 MICRONS      533022      39  

I need to represent the table in the following format, but I just need this kind of representation for single row

ColName       ColValue
-----------------------------
ScripName      20 MICRONS
ScripCode      533022    
Price          39

so that I can directly bind the data to the datalist control.

like image 848
Ish Tech Avatar asked Mar 17 '11 09:03

Ish Tech


People also ask

How do I convert column values to rows?

Here's how you can transpose cell content: Copy the cell range. Select the empty cells where you want to paste the transposed data. On the Home tab, click the Paste icon, and select Paste Transpose.

Is there a SQL function that can convert data types?

SQL Server automatically converts the data from one data type to another. For example, when a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds. GETDATE() implicitly converts to date style 0. SYSDATETIME() implicitly converts to date style 21.

How does cross apply work in SQL?

The CROSS APPLY operator is semantically similar to INNER JOIN. It retrieves all the records from the table where there are corresponding matching rows in the output returned by the table valued function.


2 Answers

declare @T table (ScripName varchar(50), ScripCode varchar(50), Price int)
insert into @T values ('20 MICRONS', '533022', 39)

select 
  'ScripName' as ColName,
  ScripName as ColValue
from @T
union all
select 
  'ScripCode' as ColName,
  ScripCode as ColValue
from @T
union all
select 
  'Price' as ColName,
  cast(Price as varchar(50)) as ColValue
from @T
like image 140
Mikael Eriksson Avatar answered Oct 21 '22 16:10

Mikael Eriksson


select 'ScriptName', scriptName from table
union all
select 'ScriptCode', scriptCode from table
union all
select 'Price', price from table
like image 31
Sachin Shanbhag Avatar answered Oct 21 '22 18:10

Sachin Shanbhag