如何使用insert插入select到存储过程?

时间:2017-01-14 19:36:52

标签: sql

我尝试创建存储过程,但我有语法错误,我不知道要改变什么。我想从select查询中接收到“@cartypeID”的数字,用于插入汽车类型编号,下面是插入代码。

create PROCEDURE AddCar (@CarFleetID int,@CarModelName nvarchar(50),@CarNumber nvarchar(50),@CurrentMiles int,@ImageFileName nvarchar(50),@IsOk2Rent bit)
 AS
 IF (SELECT COUNT(1) FROM CarFleet WHERE CarFleetID =@CarFleetID ) = 1
 BEGIN
     RETURN -1
 END ELSE
 BEGIN

   declare @cartypeID int
   @cartypeID= select CarFleet.CarFleetID
  from CarFleet join CarTypes on CarFleet.CarTypeID=CarTypes.CarTypeID join CarModels on CarTypes.CarModelID=CarModels.CarModelID
     where @CarModelName=CarModels.CarModelName

     INSERT INTO CarFleet(CarFleetID,CarTypeID,CarNumber,CurrentMiles,ImageFileName,IsOk2Rent)
VALUES(@CarFleetID, @cartypeID, @CarNumber,@CurrentMiles,@ImageFileName,@IsOk2Rent)

 END

1 个答案:

答案 0 :(得分:0)

我认为

create PROCEDURE AddCar (@CarFleetID int,@CarModelName nvarchar(50),@CarNumber nvarchar(50),@CurrentMiles int,@ImageFileName nvarchar(50),@IsOk2Rent bit)
     AS
     IF (SELECT COUNT(1) FROM CarFleet WHERE CarFleetID =@CarFleetID ) = 1
     BEGIN
         RETURN -1
     END ELSE
     BEGIN


         INSERT INTO CarFleet ( 
             CarFleetID
            ,CarTypeID
            ,CarNumber
            ,CurrentMiles
            ,ImageFileName,IsOk2Rent) 
       select 
              CarFleet.CarFleetID
              ,@cartypeID
              ,@CarNumber
              ,@CurrentMiles
              ,@ImageFileName,@IsOk2Rent
      from CarFleet 
      join CarTypes on CarFleet.CarTypeID=CarTypes.CarTypeID 
      join CarModels on CarTypes.CarModelID=CarModels.CarModelID
      where @CarModelName=CarModels.CarModelName
     END