简体   繁体   中英

How can I set order counting in insert statement SQL Server?

I tried to copy data from database to another database

I have this query

 insert into d1.dbo.Category(Id, Name, CategoryTemplateId, 
                             ParentCategoryId, PictureId, PageSize, 
                             AllowCustomersToSelectPageSize, 
                             ShowOnHomePage, IncludeInTopMenu, 
                             SubjectToAcl, LimitedToStores, Published, 
                             Deleted, DisplayOrder, 
                             CreatedOnUtc, UpdatedOnUtc)
    select 
        (ItemID + 25), ItemName, 1,
        (CategoryID + 16), '', 6,
        1, 1, 1, 0, 0, 1, 0, 1,
        iif(CreateDate is null, GETDATE(), CreateDate),
        iif(LastModifyDate is null, GETDATE(), LastModifyDate)
    from 
        d2.dbo.Item

It works fine. The question is: there is a column DisplayOrder if I use this syntax it will insert 1 in al the rows, but what I really need is to count 1,2,3,4,.. etc

Depends on (CategoryID + 16) until (CategoryID + 16) changed it start count from 1 again

Please help

Use row_number() over (partition by CategoryId order by (select null)) to populate an increasing value in DisplayOrder . (Note: The + 16 is redundant in the partition by .)

Also, instead of this construct:

iif(CreateDate is null,GETDATE(),CreateDate)

Use the simpler, more standard syntax:

coalesce(CreateDate, GETDATE())

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