这是一种方法,仅适用于 MAX 长度;您可以将其用作起点并修改/扩展它以在结果表中包含更多信息:
create table dbo.Results (
TableName sysname not null,
ColumnName sysname not null,
MaxLength int not null default 0,
primary key (TableName, ColumnName)
)
insert into dbo.Results (TableName, ColumnName)
select object_name(sc.object_id), sc.name
from sys.columns sc
join sys.types st
on sc.system_type_id = st.system_type_id
-- get data for varchar(max) columns only
where st.name = 'varchar' and sc.max_length = -1
declare @TableName sysname, @ColumnName sysname, @sql nvarchar(max)
declare TablesAndColumns cursor local fast_forward
for
select TableName, ColumnName
from dbo.Results
open TablesAndColumns
fetch next from TablesAndColumns into @TableName, @ColumnName
while @@fetch_status = 0
begin
set @sql = 'update dbo.Results set MaxLength = (select isnull(max(len(' + @ColumnName + ')),0) ' +
' from ' + @TableName + ') ' +
' where TableName = ''' + @TableName + ''' and ColumnName = ''' + @ColumnName + ''''
print @sql
exec sp_executesql @sql
fetch next from TablesAndColumns into @TableName, @ColumnName
end
close TablesAndColumns
deallocate TablesAndColumns
select * from dbo.Results
使用游标和动态 SQL 并不总是一个好主意,但对于像这样的一次性系统任务来说,这是一种合理的方法。