在此上下文中不允许子查询。只允许标量表达式

时间:2013-06-12 10:47:58

标签: sql-server stored-procedures

我的存储过程在SQL Server 2008中工作正常,但是当我尝试在SQL Server 2005中运行相同的过程时,它会抛出此错误说明

在此上下文中不允许使用子查询。只允许使用标量表达式。

以下是我的sp

USE dbEmployeeManagementSystem
GO
CREATE PROCEDURE [dbo].spInsertTaskAssignmentsample
(
@Username nvarchar(50),
@ProjectName nvarchar(50),
@ClientName nvarchar(50),
@Status nvarchar(50),
@StartDate nvarchar(50),
@EndDate nvarchar(50),
@ReportingManager nvarchar(50),
@Comments nvarchar(100)
 )
AS
BEGIN   
INSERT INTO tblTaskAssignment
(EID,ProjectName, ClientName, Status, StartDate, EndDate,ReportingManager,Comments) 
Values
((SELECT top 1 EID FROM tblLogin WHERE Username=@Username), @ProjectName, @ClientName, @Status, @StartDate, @EndDate,@ReportingManager,@Comments)
END

请帮助我,是否有任何解决方案或sql 2005 doest支持此类查询?

提前致谢。

4 个答案:

答案 0 :(得分:10)

您可以使用SELECT 代替 VALUES子句:

INSERT INTO tblTaskAssignment
(EID,ProjectName, ClientName, Status, StartDate, EndDate,ReportingManager,Comments) 
SELECT (SELECT TOP 1 EID FROM tblLogin WHERE Username=@Username), @ProjectName, @ClientName, @Status, @StartDate, @EndDate,@ReportingManager,@Comments

答案 1 :(得分:4)

SQL Server 2005不支持此功能。它于2008年推出。

您可以将子查询的结果分配给变量,并在VALUES子句中使用它。

答案 2 :(得分:2)

备选方案1:

您可以将EID放入如下变量中:

    CREATE PROCEDURE [dbo].spInsertTaskAssignmentsample
    (
    @Username nvarchar(50),
    @ProjectName nvarchar(50),
    @ClientName nvarchar(50),
    @Status nvarchar(50),
    @StartDate nvarchar(50),
    @EndDate nvarchar(50),
    @ReportingManager nvarchar(50),
    @Comments nvarchar(100)
     )
    AS
    BEGIN

    DECLARE @EID INT;
    SET @EID = (SELECT top 1 EID FROM tblLogin WHERE Username=@Username);

    INSERT INTO tblTaskAssignment
    (EID,ProjectName, ClientName, Status, StartDate, EndDate,ReportingManager,Comments) 
    Values
    (@EID, @ProjectName, @ClientName, @Status, @StartDate, @EndDate,@ReportingManager,@Comments)
    END

如果EID不是整数类型,则必须在声明语句

中指定该类型

备选方案2: 使用SELECT子句

    CREATE PROCEDURE [dbo].spInsertTaskAssignmentsample
    (
    @Username nvarchar(50),
    @ProjectName nvarchar(50),
    @ClientName nvarchar(50),
    @Status nvarchar(50),
    @StartDate nvarchar(50),
    @EndDate nvarchar(50),
    @ReportingManager nvarchar(50),
    @Comments nvarchar(100)
     )
    AS
    BEGIN

    INSERT INTO tblTaskAssignment
    (EID,ProjectName, ClientName, Status, StartDate, EndDate,ReportingManager,Comments) 
    SELECT TOP 1 EID, @ProjectName, @ClientName, @Status, @StartDate, @EndDate,@ReportingManager,@Comments FROM tblLogin WHERE Username=@Username 
    END

答案 3 :(得分:0)

您可以使用SELECT 代替 VALUES子句:

INSERT INTO tblTaskAssignment
(EID,ProjectName, ClientName, Status, StartDate, EndDate,
    ReportingManager,Comments) 
SELECT top 1 EID, @ProjectName, @ClientName, @Status, @StartDate, @EndDate,
    @ReportingManager,@Comments
FROM tblLogin WHERE Username=@Username

(虽然请注意,根据Martin Smith和ta.speot.is之间的讨论,这确实假设tblLogin中至少有一行匹配@Username