简体   繁体   中英

table variable with other parameter insert

Here is my procedure

CREATEPROCEDURE mysp
    @id int
    @param1 int
    @param2 int
    @param3 datetime
    @param4 bit
AS
    DECLARE @tv TABLE
    ( 
         param1 INT
    )
    INSERT INTO @tv ( param1 )
    SELECT param1 FROM tbl1 WHERE id = @id and IsActive = 1


    INSERT INTO tbl2
    (   
     id
    ,param1 
    ,param2 
    ,param3 
    ,param4 
    )
    VALUES
    (
     // all recors from @tv
    ,@param1 
    ,@param2 
    ,@param3 
    ,@param4 
   )

@tv will have multiple records i want to insert each value of param1 in @tv insert into another table along with other parameter param1, param2, param3, param4. Something like this

Is there a way of doing this. i dont want to use any cursor for this .

Thanks. help will be really appreciated.

It looks to me like you can simplify the whole thing to:

CREATE PROCEDURE mysp
    @id INT ,
    @param1 INT ,
    @param2 INT ,
    @param3 DATETIME ,
    @param4 BIT
AS
    INSERT  INTO tbl2
            ( id ,
              param1 ,
              param2 ,
              param3 ,
              param4
            )
            SELECT  param1 ,
                    @param1 ,
                    @param2 ,
                    @param3 ,
                    @param4
            FROM    tbl1
            WHERE   id = @id
                    AND isActive = 1

    GO

change your second insert like this.

INSERT INTO tbl2
            (id,param1,param2,param3,param4)
SELECT param1,@param1,@param2,@param3,@param4
FROM   @tv 

or You can directly do a insert from tbl1 no need to declare a table variable (@tv)

INSERT INTO tbl2
            (id,param1,param2,param3,param4)
SELECT param1,@param1,@param2,@param3,@param4
FROM   tbl1 WHERE id = @id and IsActive = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM