SQL 服务器:table 的动态 RowNumber 更新
SQL Server: dynamic RowNumber update of a table
我正在尝试使用 RowNumber 更新数据库的所有行...
在我的循环 运行 到我的 table 中,我得到了这两个动态语句:
Set @SqlStringOne = ('
Alter Table ' +@Schema+'.'+@Table+'
Add RowID int;
')
Exec(@SqlStringOne);
(正在工作并将新的 RowID (RowNum) 列添加到我的 table 中)
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
但是更新不起作用...
提前致谢
您的查询有两个问题。
1-当你想使用FROM更新时,你需要使用别名。
2- 在您的订单中,您需要将 table 名称作为字符串传递。
像下面这样更改您的查询。
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
您随时可以打印 sql 查询以检查是否存在任何问题。
我不明白order by
。为什么不这样做呢?
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;
您可以在 update
中使用 x
。我不明白 order by
对系统 table 的引用。它应该返回一个常量,所以你不妨使用 (select null)
.
我正在尝试使用 RowNumber 更新数据库的所有行...
在我的循环 运行 到我的 table 中,我得到了这两个动态语句:
Set @SqlStringOne = ('
Alter Table ' +@Schema+'.'+@Table+'
Add RowID int;
')
Exec(@SqlStringOne);
(正在工作并将新的 RowID (RowNum) 列添加到我的 table 中)
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
但是更新不起作用...
提前致谢
您的查询有两个问题。
1-当你想使用FROM更新时,你需要使用别名。
2- 在您的订单中,您需要将 table 名称作为字符串传递。
像下面这样更改您的查询。
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
您随时可以打印 sql 查询以检查是否存在任何问题。
我不明白order by
。为什么不这样做呢?
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;
您可以在 update
中使用 x
。我不明白 order by
对系统 table 的引用。它应该返回一个常量,所以你不妨使用 (select null)
.