Subquery on iinsert

  • Hi All,

    In a stored procedure before performing the insert I want to get the max value of a column and add 1 to it since it is part of the key. the Email, CapNo and Image are passed into the stored procedure and I have a variable declared as @ImageNo. How do I incorporate the subquery into the insert statement so that the returned value becomes @ImageNo in the insert statement.

    I have the following code:

    my subquery is:

    select

    isnull(max(imageno),0)+1 as ImageNo

    from

     mytable where customeremail = @CustomerEmail and capno = @CapNo

    and my insert statement at the moment is simply:

    INSERT

    INTO [MyDB].[dbo].[mytable]

    ([CustomerEmail]

    ,[CapNo]

    ,[ImageNo]

    ,[Graphic])

    VALUES

    (@CustomerEmail,

    @CapNo

    ,

    @ImageNo

    ,

    @Graphic

    )

  • INSERT INTO [dbo].[mytable]

         ( [CustomerEmail]

          ,[CapNo]

          ,[ImageNo]

          ,[Graphic])

      SELECT @CustomerEmail

            ,@CapNo

            ,(SELECT IsNull(Max(imageno),0)+1

                FROM [dbo].[mytable]

               WHERE customeremail = @CustomerEmail

                 AND capno = @CapNo

             )

            ,@Graphic

  • Hi MKEast,

    I tried the above but I receive error:

    Msg 1046, Level 15, State 1, Procedure InsertImage, Line 34

    Subqueries are not allowed in this context. Only scalar expressions are allowed.

     

    So I made the subquery a function and have changed my select statement to be:

    ..........

    @CapNo

    ,

    dbo.FunctionImageNo(@CustomerEmail, @CapNo),

    @Graphic

    I dont get a compilation error now, but instead an invalid object name dbo.FuntionImageNo

     

  • I think there is no need for a function for this, just get the result into @ImageNo using below select statement and use the variable in insert

    select

    @ImageNo=isnull(max(imageno),0)+1 from mytable where customeremail = @CustomerEmail and capno = @CapNo

     

     

  • What are the data types of the variables and columns? I retested the query using all int datatypes without any problems.  It worked perfectly.

     

  • Sorry,  I didn't see the subtle change from 'Values' to Select. I have changed to Select and now works. THanks Very much.

    Incidently, if I did want to do this as a function, how would I make the call to the function?

  • Select dbo.FunctionImageNo(@CustomerEmail, @CapNo), Cola from ...

     

    However this would result in a cursor like process.  In this case it is really not a good idea to use a function.

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply