我需要准备一个动态查询来查找sql server列中所有行的长度。假设一个100行的表格是否有10列。我需要动态查找每列的行长。
答案 0 :(得分:0)
假设您的所有列都是字符串列,尽管len
函数仍然可以正常工作。
-- replace 'mytable' with the actual table name
declare @tableName nvarchar(128) = 'mytable';
declare @queryToRun nvarchar(max) = '';
-- IMPORTANT: following query is putting each column name as len_columnName
select @queryToRun = @queryToRun + ', len([' + c.name + ']) as [len_' + c.name + ']
'
from sys.tables as t
inner join sys.columns as c on t.object_id = c.object_id
where t.name = @tableName
-- removing the first comma
set @queryToRun = SUBSTRING(@queryToRun, 2, len(@queryToRun) - 1);
-- creating the query with dynamic column names
set @queryToRun = 'select ' + @queryToRun + ' from ' + @tableName;
--print @queryToRun
exec (@queryToRun)
答案 1 :(得分:0)
您可以使用sys.tables
和sys.all_columns
declare @Sql nvarchar(max)='select '
select @Sql=@sql+'Sum(len('+QUOTENAME(c.name)+')) as Len'+QUOTENAME(c.name)+',' from sys.tables t join sys.all_columns c on t.object_id=c.object_id
where t.Name='YourTableName'
set @Sql = left(@Sql,len(@sql)-1)+' from YourTableName'
select @Sql
答案 2 :(得分:0)
尝试使用此脚本,您将动态获取表中各列的数据长度
IF OBJECT_ID('dbo.LenghtOfRows')IS NOT NULL
DROP TABLE LenghtOfRows
CREATE TABLE LenghtOfRows (
Id Int IDENTITY,
Sqlode nvarchar(max)
)
DECLARE @SQL NVARCHAR(max),
@MinId INT,
@MaxId INT,
@tableName Varchar(100) ='StudentLabExamScore', --Give Table name here
@GetSQL NVARCHAR(max)
SET @SQL = 'SELECT ''SELECT DATALENGTH(''+COLUMN_NAME+'') As Len_'' +COLUMN_NAME +'' FROM ''+TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '''+@tableName+''''
PRINT @SQL
INSERT INTO LenghtOfRows(Sqlode)
EXEC ( @SQL)
SELECT @MinId = MIN(Id) from LenghtOfRows
SELECT @MaxId = MAX(Id) from LenghtOfRows
WHILE (@MInId <=@MaxId)
BEGIN
SELECT @GetSQL= Sqlode FROM LenghtOfRows WHERE id=@MInId
EXEC (@GetSQL)
PRINT @GetSQL
SET @MInId=@MInId+1
END