Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

Columns to row

$
0
0
I have 2 tables where i can search on PK. However 1 table has other columns than the other. Is there a way I can use the same query (except for changing tablename) with having the columns converted to rows?[code="sql"]CREATE TABLE [dbo].[Test]( [PK] [int] IDENTITY(1,1) NOT NULL, [COLUMN1] [nvarchar](50) NOT NULL, [COLUMN2] [nchar](10) NULL, [COLUMN3] [nchar](10) NULL, [COLUMN4] [nchar](10) NULL, CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ( [PK] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOINSERT INTO [dbo].[Test] ([COLUMN1] ,[COLUMN2] ,[COLUMN3] ,[COLUMN4]) VALUES ('Valuein1r1' ,'Valuein2r1' ,'VAluein3r1' ,'Valuein4r1')GOINSERT INTO [dbo].[Test] ([COLUMN1] ,[COLUMN2] ,[COLUMN3] ,[COLUMN4]) VALUES ('Valuein1r2' ,'Valuein2r2' ,'VAluein3r2' ,'Valuein4r2')GOINSERT INTO [dbo].[Test] ([COLUMN1] ,[COLUMN2] ,[COLUMN3] ,[COLUMN4]) VALUES ('Valuein1r3' ,'Valuein2r3' ,'VAluein3r3' ,'Valuein4r3')GOINSERT INTO [dbo].[Test] ([COLUMN1] ,[COLUMN2] ,[COLUMN3] ,[COLUMN4]) VALUES ('Valuein1r4' ,'Valuein2r4' ,'VAluein3r4' ,'Valuein4r4')GOselect *from testwhere PK = 1[/code]This will get me:1 Value in 1 Value in 2 VAlue in 3 Value in 4However, what i would like as result is:[code="sql"]select 1, 'Value in 1' unionselect 1, 'Value in 2' unionselect 1, 'Value in 3' unionselect 1, 'Value in 4' [/code]Is there a way to achieve this, and when having a 'test2' i only need to change the tablename in the select?

Viewing all articles
Browse latest Browse all 3145

Trending Articles