透视整数

时间:2018-03-31 15:03:13

标签: sql-server pivot

我在转换varchar值时收到转换失败的错误,将整数发送到varchar查询。

  

转换varchar值'查询'

时转换失败

查询:

ALTER PROCEDURE [dbo].[GetConsolidatedConducts]
@sectionID nvarchar(20),
@schoolID int,  
@schoolYearID int
AS      
BEGIN
DECLARE  @PivotColumns VARCHAR(MAX),@SQL VARCHAR(MAX);

SET @PivotColumns = STUFF((SELECT distinct ',' + QUOTENAME(c.CoreValues) as CoreValues
            FROM Conducts c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @SQL = 'select * from
        (select DISTINCT C.CoreValues,
        CSG.StudentID,
        CONCAT(S.Firstname ,'' ''+S.Lastname) as StudentName,
        CSG.Q1 from
        ConductsStudentGrade CSG
        LEFT JOIN Conducts C
        on CSG.CVID = C.CVID
        LEFT JOIN EnrollmentStatus ES
        on CSG.StudentID = ES.StudentNumber 
        Left Join Students S with (nolock)
        on es.StudentNumber = s.StudentNumber
        where CSG.SchoolID = ' + @schoolID + ' and CSG.SchoolYearID = ' + @schoolYearID + '
        and es.SectionID =  ' + @sectionID + ') X
        PIVOT (MAX([Q1])
                     FOR [CoreValues] IN (' + @PivotColumns + ')) AS p';
EXEC(@SQL)
END

2 个答案:

答案 0 :(得分:0)

为了使转换失败安全,您应该这样做:

ALTER PROCEDURE [dbo].[GetConsolidatedConducts]
@sectionID nvarchar(20),
@schoolID int,  
@schoolYearID int
AS      
BEGIN
    DECLARE  @PivotColumns VARCHAR(MAX),@SQL VARCHAR(MAX);

    SET @PivotColumns = STUFF((SELECT distinct ',' + QUOTENAME(c.CoreValues) as CoreValues
                FROM Conducts c
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')

    SET @SQL = 'select * from
            (
                select DISTINCT 
                    CoreValues=CAST(C.CoreValues as varchar(max)), /* cast the value */
                    CSG.StudentID,
                    CONCAT(S.Firstname ,'' ''+S.Lastname) as StudentName,
                    CSG.Q1 
                from
            ConductsStudentGrade CSG
                LEFT JOIN Conducts C
                    on CSG.CVID = C.CVID
                LEFT JOIN EnrollmentStatus ES
                    on CSG.StudentID = ES.StudentNumber 
                Left Join Students S with (nolock)
                    on es.StudentNumber = s.StudentNumber
            where CSG.SchoolID = ' + @schoolID + ' and CSG.SchoolYearID = ' + @schoolYearID + '
            and es.SectionID =  ' + @sectionID + ') X
            PIVOT (MAX([Q1])
                         FOR [CoreValues] IN (' + @PivotColumns + ')) AS p';
    EXEC(@SQL)
END

答案 1 :(得分:0)

您必须将您的整数转换为varchars:

where CSG.SchoolID = ' + convert(varchar(20), @schoolID) + 
' and CSG.SchoolYearID = ' + convert(varchar(20), @schoolYearID) + '