Sunday, February 26, 2017

How to get Multiple Insert or Update ID

Recently i assign a task in which I need to log every record that is inserted or updated in table and insert in to second table . we can do it by using trigger but in my case there are some limitation so i am using this approach  .

In my case there is a store procedure that is doing is used to insert or update the table,

So i make a this
ALTER PROCEDURE [Sp_name] 
AS 
  BEGIN 
      DECLARE @Last_Insterted_Id INTEGER=0 
      DECLARE @Updated_Id INTEGER=0 
      DECLARE @listStr NVARCHAR(max) 

      INSERT INTO [table] 
                  (col) 
      VALUES      (values) 

      -- LOG 
      INSERT INTO [table] 
                  (col) 
      output      inserted.id 
      INTO @mytable -- inserted id  
      SELECT @Last_Insterted_Id = id 
      FROM   @mytable -- the Inserted id      
      -- In update case you need to get the IDS 
      UPDATE [table_name] 
      SET    a = @A 
      output inserted.id 
      INTO @mytable -- get the updated id      
      WHERE  col = @A 

      SELECT @Updated_Id = id 
      FROM   @mytable -- the updated id   
      SELECT col 
      FROM   table 
      WHERE  admin_user_rights_id = @Updated_Id 
  -- in which you get the recently update id 
  END 


If in case you have multiple Ids so we will think for cursor use these ids and insert or update right ?
:) I use the other approach .If we are inserting/updating multiple ids we get in   @mytable

so we can separate with comma use IN clause and get all the columns

       
SELECT @listStr = COALESCE(@listStr+',' ,'') +convert(nvarchar(20), Id)
FROM @mytable
SELECT @listStr


INSERT INTO table_name 
            (col) 
SELECT col 
WHERE  id IN(SELECT data 
             FROM   dbo.Split(@listStr, ',')) -- in this we get all the ids with comma separate 

use same for update ...


P.S i try to start blogging may be i am not able try to explain perfectly but may be this help for you

Refernce links

OUTPUT Keyword
http://stackoverflow.com/questions/12566493/how-can-i-assign-inserted-output-value-to-a-variable-in-sql-server


COALESCE Keyword
https://blog.sqlauthority.com/2008/06/04/sql-server-create-a-comma-delimited-list-using-select-clause-from-table-column/









No comments:

Post a Comment