Insert Row Base on Value into table

Analyst_SQL 3,576 Reputation points
2022-06-17T18:07:36.95+00:00

I want if i pass parameter of 5 qty and input 122 value in CID col ,then in table #tbl_ContD 5 row get insert

 create table  #tbl_ContD (CID int ,S_no int)   
  
  
 Insert into #tbl_ContD values (122,1)  
 Insert into #tbl_ContD values (122,2)  
  Insert into #tbl_ContD values (122,3)  
   Insert into #tbl_ContD values (122,4)  
    Insert into #tbl_ContD values (122,5)  
	  

212528-image.png

Developer technologies | Transact-SQL
SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2022-06-17T19:15:58.577+00:00

    If you have a large number of rows to be processed, you should use a number table to assist your query.
    If you just have a few rows, you can even use recursive to get your result on the fly.
    declare @CID int=122, @S_no int =5
    ;with mycte as (
    select @CID CID,1 as S_no
    union all
    Select CID, S_no+1 as S_no
    from mycte where S_no<@S_no)

     Insert into #tbl_ContD(CID,S_no)  
    select CID,S_no from mycte  
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2022-06-17T18:29:57.633+00:00
    create table  #tbl_ContD (CID int ,S_no int)   
          
          
      --Insert into #tbl_ContD values (122,1)  
      --Insert into #tbl_ContD values (122,2)  
      -- Insert into #tbl_ContD values (122,3)  
      --  Insert into #tbl_ContD values (122,4)  
      --   Insert into #tbl_ContD values (122,5)  
      
      declare @CID int=122, @S_no int =5  
      Insert into #tbl_ContD(CID,S_no)  
      
      select CID, Number from (select @CID CID) t  
      cross apply(  
       SELECT Number FROM master.dbo.spt_values  where  
       type = 'P' and Number >= 1 and Number <= @S_no) d  
      
      
    select * from #tbl_ContD  
      
     drop table #tbl_ContD  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.