')'附近的语法不正确。程序中

时间:2018-12-18 09:34:29

标签: sql-server

> ret_data
   V1 V2
1: NA NA

2 个答案:

答案 0 :(得分:5)

由于SQL字符串内的单引号,您的SQL不正确。您需要逃避这些。例如:

IF NOT EXISTS (SELECT * FROM sys.procedures WHERE name = 'spGetEmployeeListWithOutputVariable')
BEGIN
        EXEC('CREATE PROCEDURE spGetEmployeeListWithOutputVariable
        @NoOfRecord INT OUTPUT
        AS
        BEGIN
        SELECT @NoOfRecord = COUNT(EmployeeID)
        FROM EmployeeData
        SELECT 
            employee.EmployeeId,
            employee.EmployeeName,
            employee.ContactNumber,
            STUFF((SELECT '','' + hobby.Name FROM Hobbies AS hobby    
                            JOIN dbo.MapHobbiesData AS MapEmpHob 
                                ON MapEmpHob.HobbiesId=hobby.HobbiesId     
                            WHERE MapEmpHob.EmployeeId=employee.EmployeeId
                            FOR XML PATH(''''))
                ,1,1,'''')  Hobbies,
                NoOfEmpRecords = @NoOfRecord
        FROM EmployeeData AS employee
        END')
END

答案 1 :(得分:0)

将双反逗号(')替换为单反逗号(')

EXEC('CREATE PROCEDURE spGetEmployeeListWithOutputVariable
        @NoOfRecord INT OUTPUT
        AS
        BEGIN
        SELECT @NoOfRecord = COUNT(EmployeeID)
        FROM EmployeeData
        SELECT 
            employee.EmployeeId,
            employee.EmployeeName,
            employee.ContactNumber,
            STUFF((SELECT '','' + hobby.Name FROM Hobbies AS hobby    
                            JOIN dbo.MapHobbiesData AS MapEmpHob 
                                ON MapEmpHob.HobbiesId=hobby.HobbiesId     
                            WHERE MapEmpHob.EmployeeId=employee.EmployeeId
                            FOR XML PATH(''''))
                ,1,1,'''')  Hobbies,
                NoOfEmpRecords = @NoOfRecord
        FROM EmployeeData AS employee
        END')