简体   繁体   中英

SQL Server: dynamic RowNumber update of a table

I m trying to update all rows of my database with a RowNumber ...

In my loop running through my tables I got these two dynamic statements:

Set @SqlStringOne = ('
            Alter Table ' +@Schema+'.'+@Table+'
            Add RowID int;
            ')
    Exec(@SqlStringOne); 

(is working and adding a new RowID (RowNum) Column into my table) and

Set @SqlStringTwo = ('
            update ' +@Schema+'.'+@Table+'
            Set  x.RowID = x.RowID_x
            from
            (select 
             RowID,
             ROW_NUMBER() OVER 
            (ORDER BY (Select TOP 1 COLUMN_NAME from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '+@Table+')) as RowID_x
            from '+@Schema+'.'+@Table+') x
            ');
    Exec dbo.sp_executesql @stmt = @SqlStringTwo

But the update is not working ...

Thanks in advance

You have two issues in your query.

1- When you want to update using FROM, you need to use alias.

2- in your order by, you need to pass table name as a string.

Change your query like following.

Set @SqlStringTwo = ('
            update x 
            Set  x.RowID = x.RowID_x
            from
            (select 
             RowID,
             ROW_NUMBER() OVER 
            (ORDER BY (Select TOP 1 COLUMN_NAME from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '''+@Table+''')) as RowID_x
            from '+@Schema+'.'+@Table+') x
            ');
    Exec dbo.sp_executesql @stmt = @SqlStringTwo

You can always print your sql query to check for any issues.

I don't understand the order by . Why not just do this?

update x
    set x.RowID = x.RowID_x
    from (select  t.*,
                  row_number() over (order by (select null)) as rowid_x
          from ' + @Schema + '.' + @Table + '
         ) x;

You can use x in the update . I don't understand the reference to the system table for the order by . It should be returning a constant, so you might as well use (select null) .

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