我尝试使用以下动态SQL迭代表中的列,并获取表中每个字段的百分比弹出窗口。这是脚本:
CREATE TABLE [dbo].[PercentPop] (
[Field Name] VARCHAR(255),
[Percent Pop] DECIMAL(6, 3)
)
DECLARE @rowCount as INT
SET @rowCount = (SELECT MAX([Ordinal_Position]) FROM information_schema.columns)
DECLARE @i as INT
SET @i = 1
DECLARE @Column as varchar(255)
DECLARE @Percent as DECIMAL(6, 3)
WHILE @i <= @rowCount
BEGIN
SET @Column = (SELECT [Column_name] FROM information_schema.columns
WHERE [table_name] = 'myTable' AND [Ordinal_Position] = @i)
SET @Percent = (SELECT 100.0 * SUM(CASE WHEN @Column <> '' THEN 1 ELSE 0 END) / COUNT(*)
AS ColumnPercent FROM myTable)
INSERT INTO [dbo].[PercentPop] VALUES (@Column, @Percent)
SET @i = @i + 1
END
此脚本的结果会正确生成字段名称,但每个百分比都是100%。我想知道某些事情是否正确迭代,因为第一个字段是100%填充的,但我知道后续字段不是。