У меня есть следующий запрос для преобразования строк в столбцы.Мне нужно пометить столбцы с именем _ в конце имени столбца.
Следующая часть запроса ниже:
as QUOTENAME(FieldName) + '_name'
выдает следующую ошибку:
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '('.
Запрос:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(FieldName) as QUOTENAME(FieldName) + '_name'
from [LookUp].[CustomField]
where FieldTable = 'Clientbackground'
group by FieldName, CustomFieldID
order by CustomFieldID
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select isRequired, FieldName
from [LookUp].[CustomField]
where FieldTable = ''Clientbackground''
) x
pivot
(
max(isRequired)
for FieldName in (' + @cols + N')
) p '
exec sp_executesql @query;
Кто-нибудь знает, как я могу это исправить?
CREATE TABLE [LookUp].[CustomField](
[CustomFieldID] [smallint] IDENTITY(1,1) NOT NULL,
[FieldTable] [nvarchar](100) NOT NULL,
[FieldName] [nvarchar](100) NOT NULL,
[Label] [nvarchar](500) NOT NULL,
[Description] [nvarchar](500) NOT NULL,
[IsVisible] [int] NOT NULL,
[IsRequired] [int] NOT NULL,
[IsAutoAlert] [int] NOT NULL,
CONSTRAINT [PK_CustomField] PRIMARY KEY CLUSTERED
(
[CustomFieldID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
INSERT [LookUp].[CustomField] ([CustomFieldID], [FieldTable], [FieldName], [Label], [Description], [IsVisible], [IsRequired], [IsAutoAlert]) VALUES (148, N'ClientBackGround', N'FieldName1', N'update label', N'update description', 1, 0, 0)
GO
INSERT [LookUp].[CustomField] ([CustomFieldID], [FieldTable], [FieldName], [Label], [Description], [IsVisible], [IsRequired], [IsAutoAlert]) VALUES (149, N'ClientBackGround', N'FieldName2', N'update label', N'update description', 1, 0, 0)
GO
INSERT [LookUp].[CustomField] ([CustomFieldID], [FieldTable], [FieldName], [Label], [Description], [IsVisible], [IsRequired], [IsAutoAlert]) VALUES (150, N'ClientBackGround', N'FieldName3', N'update label', N'update description', 1, 0, 0)
GO
INSERT [LookUp].[CustomField] ([CustomFieldID], [FieldTable], [FieldName], [Label], [Description], [IsVisible], [IsRequired], [IsAutoAlert]) VALUES (151, N'ClientBackGround', N'FieldName4', N'update label', N'update description', 1, 0, 0)
GO
INSERT [LookUp].[CustomField] ([CustomFieldID], [FieldTable], [FieldName], [Label], [Description], [IsVisible], [IsRequired], [IsAutoAlert]) VALUES (152, N'ClientBackGround', N'FieldName5', N'update label', N'update description', 1, 0, 0)
GO
INSERT [LookUp].[CustomField] ([CustomFieldID], [FieldTable], [FieldName], [Label], [Description], [IsVisible], [IsRequired], [IsAutoAlert]) VALUES (153, N'ClientBackGround', N'FieldName6', N'update label', N'update description', 1, 0, 0)