SQL SERVER: How to generate auto ID when inserting bulk data into table

T.Zacks 3,996 Reputation points
2022-03-16T10:50:11.613+00:00

see my sql.
declare @XML xml=N'<?xml version="1.0" encoding="utf-16"?>
<root>
<SectionLineItemDto>
<Section>Model Output</Section>
<LineItem>Products</LineItem>
</SectionLineItemDto>
<SectionLineItemDto>
<Section>Test Output</Section>
<LineItem>Test Products</LineItem>
</SectionLineItemDto>
</root>'

	SELECT 'AAPL',Section,'I' AS Action,  
	(Select ROW_NUMBER() OVER (PARTITION BY SectionID ORDER BY InsertedOn DESC) FROM tblSectionTemplate WHERE TickerID='AAPL') RowNum,  
	GetDate() AS InsertedOn,'ADM' AS InsertedBy FROM  
	(  
		SELECT d.v.value('(Section/text())[1]', 'VARCHAR(MAX)') AS Section  
		FROM @xml.nodes('/root/SectionLineItemDto') AS d(v)  
	) X	  

When select query execute then ROW_NUMBER() function returning null. but i want it should return 1 for first records. 2 for second records etc.

where my is my mistake for ROW_NUMBER() not returning auto id. thanks

Developer technologies | C#
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2022-03-17T05:12:41.573+00:00

    @T.Zacks , Welcome to Microsoft Q&A, based on my test, I reproduced your problem.

    I tried the following code and it could return auto id.

    SELECT 'AAPL',Section,'I' AS Action,  
           ROW_NUMBER() OVER ( PARTITION BY SectionID ORDER BY InsertedOn DESC) RowNum,  
         GetDate() AS InsertedOn,'ADM' AS InsertedBy FROM  
         (  
             SELECT d.v.value('(Section/text())[1]', 'VARCHAR(MAX)') AS Section  
             FROM @xml.nodes('/root/SectionLineItemDto') AS d(v)  
         ) X  
         inner join tblSectionTemplate on tblSectionTemplate.TickerID='AAPL'  
    

    Result:

    183908-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Naomi Nosonovsky 8,431 Reputation points
    2022-03-16T18:58:05.003+00:00

    Does this work?

    SELECT 'AAPL',Section,'I' AS Action,
     ROW_NUMBER() OVER (PARTITION BY SectionID ORDER BY (select 1) DESC) as  RowNum,
         GetDate() AS InsertedOn,'ADM' AS InsertedBy FROM
         (
             SELECT d.v.value('(Section/text())[1]', 'VARCHAR(MAX)') AS Section
             FROM @xml.nodes('/root/SectionLineItemDto') AS d(v)
         ) X    
    
    1 person found this answer helpful.
    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.