I have a table containing columns where the value is a (specification and the value) in the column. Example:
Instead of a name spec1, spec* I would like to have the actual spec name like Size as the column name and the value should be the part after the: in the string. Also my table contains 30 spec fields so I want to do it as efficient as possible.
I think I need a split and a pivot and unpivot to get this to work. But if there is a beter solution for this I am al ears. Any help is appreciated.
Here is the example code: in the string.
CREATE TABLE [dbo].[question](
[Name] [varchar](5) NOT NULL,
[articleNum] [varchar](6) NOT NULL,
[spec1] [varchar](16) NOT NULL,
[spec2] [varchar](18) NOT NULL,
[spec3] [varchar](17) NOT NULL,
[spec4] [varchar](26) NOT NULL,
[spec5] [varchar](26) NOT NULL
) ON [PRIMARY]
GO
INSERT [dbo].[question] ([Name], [articleNum], [spec1], [spec2], [spec3], [spec4], [spec5]) VALUES (N'Stone', N'477665', N'size : Small', N'Height : 0.4 meter', N'width : 2.1 meter', N' details N/A : details N/A', N' details N/A : details N/A')
GO
INSERT [dbo].[question] ([Name], [articleNum], [spec1], [spec2], [spec3], [spec4], [spec5]) VALUES (N'Stone', N'477666', N'size : Medium', N'Height : 1 meter', N'width : 4 meter', N'shape : round', N'color : black')
GO
INSERT [dbo].[question] ([Name], [articleNum], [spec1], [spec2], [spec3], [spec4], [spec5]) VALUES (N'Stone', N'777666', N'size : Large', N'Height : 1 meter', N'width : 3 meter', N'Material : stainles steel', N'color : green')
GO
INSERT [dbo].[question] ([Name], [articleNum], [spec1], [spec2], [spec3], [spec4], [spec5]) VALUES (N'Stone', N'977666', N'Height : 1 meter', N'width : 4 meter', N'shape : round', N'color : black', N' details N/A : details N/A')
GO
INSERT [dbo].[question] ([Name], [articleNum], [spec1], [spec2], [spec3], [spec4], [spec5]) VALUES (N'Stone', N'977666', N'size : Medium', N'Height : 1 meter', N'width : 4 meter', N'shape : round', N'color : black')
GO
I suggest using a column in JSON format so that you can enter the necessary items in it completely freely. Like the example below
SELECT articleNum,
Name,
JSON_VALUE(JsonColumn, '$.spec1') AS People,
JSON_VALUE(JsonColumn, '$.spec2') AS Size
FROM question
your table:
CREATE TABLE [dbo].[question](
[Name] [varchar](5) NOT NULL,
[articleNum] [varchar](6) NOT NULL,
[JsonColumn] [varchar](max) NOT NULL
) ON [PRIMARY]
INSERT [dbo].[question] ([Name], [articleNum], [spec1]) VALUES (N'Stone', N'477665', N'data as json')
GO
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.