Преобразование строк в столбцы с помощью пользовательского выражения «как» - PullRequest
0 голосов
/ 31 января 2019

У меня есть следующий запрос для преобразования строк в столбцы.Мне нужно пометить столбцы с именем _ в конце имени столбца.

Следующая часть запроса ниже:

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)

Ответы [ 2 ]

0 голосов
/ 31 января 2019

Вам нужны две переменные для столбцов - одна для столбцов в select, другая для столбцов в предложении сводки:

DECLARE @cols_p AS NVARCHAR(MAX),
      @cols_s AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols_s = 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,'')

select @cols_p = STUFF((SELECT ',' + QUOTENAME(FieldName) 
                    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_s + N' from 
             (
                select isRequired, FieldName
                from [LookUp].[CustomField]
                where FieldTable = ''Clientbackground''
            ) x
            pivot 
            (
                max(isRequired)
                for FieldName in (' + @cols_p + N')
            ) p '

exec sp_executesql @query;
0 голосов
/ 31 января 2019

Псевдоним не может быть выражением, это должно быть явное значение.Вам придется разделить ваши сводные значения на 2: одно для сводного и другое для списка SELECT.

DECLARE 
    @colsPivot AS NVARCHAR(MAX),
    @colsSelect AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @colsPivot = STUFF((SELECT ',' + QUOTENAME(FieldName)
                    from [LookUp].[CustomField]
                    where FieldTable = 'Clientbackground'
                    group by FieldName, CustomFieldID
                    order by CustomFieldID
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsSelect = 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 ' + @colsSelect + N' from 
             (
                select isRequired, FieldName
                from [LookUp].[CustomField]
                where FieldTable = ''Clientbackground''
            ) x
            pivot 
            (
                max(isRequired)
                for FieldName in (' + @colsPivot + N')
            ) p '

exec sp_executesql @query;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...