我收到“'语法不正确'。' “当我运行以下查询时。
DECLARE
@StaffID INT = 4,
@Cursorsql nvarchar(4000);
SET @Cursorsql = 'DECLARE curStaff CURSOR FOR ';
SET @Cursorsql = @Cursorsql + ' SELECT s.StaffID, o.OfficeName, s.FirstName ';
SET @Cursorsql = @Cursorsql + ' ' + 's.LastName FROM Staff s ';
SET @Cursorsql = @Cursorsql + ' INNER JOIN Offices o ON o.OfficeID = s.OfficeID ';
SET @Cursorsql = @Cursorsql + ' WHERE (s.OfficeID = @OfficeID OR @OfficeID = 0) ';
IF @StaffID > 0
SET @Cursorsql = @Cursorsql + ' AND s.StaffID = @StaffID ';
SET @Cursorsql = @Cursorsql + ' ORDER BY s.OfficeID, s.FirstName, s.LastName ';
exec (@Cursorsql);
答案 0 :(得分:0)
s.FirstName
之后你错过了一个逗号:
DECLARE
@StaffID INT = 4,
@Cursorsql nvarchar(4000);
SET @Cursorsql = 'DECLARE curStaff CURSOR FOR ';
SET @Cursorsql = @Cursorsql + ' SELECT s.StaffID, o.OfficeName, s.FirstName, ';
SET @Cursorsql = @Cursorsql + ' ' + 's.LastName FROM Staff s ';
SET @Cursorsql = @Cursorsql + ' INNER JOIN Offices o ON o.OfficeID = s.OfficeID ';
SET @Cursorsql = @Cursorsql + ' WHERE (s.OfficeID = @OfficeID OR @OfficeID = 0) ';
IF @StaffID > 0
SET @Cursorsql = @Cursorsql + ' AND s.StaffID = @StaffID ';
SET @Cursorsql = @Cursorsql + ' ORDER BY s.OfficeID, s.FirstName, s.LastName ';
exec (@Cursorsql);
答案 1 :(得分:0)
打印动态sql并检查语法错误始终是一个好主意和简单的故障排除方法。您在s.FirstName
列表中的s.LastName
和SELECT
之间缺少逗号
试试这个 -
DECLARE
@StaffID INT = 4,
@Cursorsql nvarchar(4000);
SET @Cursorsql = 'DECLARE curStaff CURSOR FOR ';
SET @Cursorsql = @Cursorsql + ' SELECT s.StaffID, o.OfficeName, s.FirstName, ';
SET @Cursorsql = @Cursorsql + ' s.LastName FROM Staff s ';
SET @Cursorsql = @Cursorsql + ' INNER JOIN Offices o ON o.OfficeID = s.OfficeID ';
SET @Cursorsql = @Cursorsql + ' WHERE (s.OfficeID = @OfficeID OR @OfficeID = 0) ';
IF @StaffID > 0
SET @Cursorsql = @Cursorsql + ' AND s.StaffID = @StaffID ';
SET @Cursorsql = @Cursorsql + ' ORDER BY s.OfficeID, s.FirstName, s.LastName ';
sp_executesql @CursorSql, N'@StaffID int', @StaffID;