我正在尝试创建一个返回表的所有列名称的查询,并且每个列的计数都不同。我有超过1400个表进行测试,其中一些有100列,所以我无法想象逐个列出colomn名称。
我对计数部分有问题,而且我想知道是否可以在子查询中执行类似EXECUTE IMMEDIATE的操作,如果没有,是否还有其他解决方案?
这是我的实际查询:
SELECT
sc.name AS columnName
, ('SELECT COUNT(DISTINCT ' || sc.name || ') FROM MyTableName') AS nb_distinct_row
FROM dbo.syscolumns sc INNER JOIN sysobjects so
ON so.id = sc.id
AND so.name = 'MyTableName'
GROUP BY sc.name
这会返回好的子查询,但我不知道如何立即执行它? 我尝试过像
这样的东西, (SELECT count(distinct sc.name) from MyTableName) As nbDistinctRow
但是'sc.name'没有被解释,并且count distinct返回1,所以这就是我尝试这种方式的原因。
我在sybase IQ数据库上工作
任何人都可以帮助我吗? 提前谢谢你。
答案 0 :(得分:0)
我找到了一种方法来完成这项工作,但它确实很笨拙。
CREATE OR REPLACE PROCEDURE FLA_distinctCols(in table_obj_id INT)
RESULT (column_name VARCHAR(128), count_distinct INT)
BEGIN
DECLARE err_notfound EXCEPTION FOR SQLSTATE VALUE '02000';
DECLARE @tablename VARCHAR(100);
DECLARE @cols VARCHAR(128);
DECLARE @nb_dist INT;
DECLARE @sql VARCHAR(30000);
DECLARE @sqltemp VARCHAR(30000);
DECLARE tables NO SCROLL CURSOR FOR
SELECT
sc.name col
, ('SELECT COUNT(DISTINCT ' || sc.name || ') INTO @nb_dist FROM ' || @tablename)
FROM dbo.syscolumns sc INNER JOIN sysobjects so
ON so.id = sc.id
AND so.name = @tablename
|| '%' ORDER BY sc.name
;
SELECT so.name INTO @tablename FROM sysobjects so WHERE so.id = table_obj_id;
create table #tablestats (
column_name varchar(128) not null,
count_distinct INT,
);
open tables WITH HOLD;
LoopTables: loop
fetch next tables into @cols, @sqltemp;
if sqlstate = err_notfound then
leave LoopTables
else
EXECUTE IMMEDIATE WITH QUOTES @sqltemp;
set @sql= 'INSERT INTO #tablestats SELECT ''' || @cols || ''', ' || @nb_dist || ';';
EXECUTE IMMEDIATE WITH QUOTES @sql;
end if
end loop LoopTables;
close tables;
SELECT column_name, count_distinct FROM #tablestats ORDER BY count_distinct DESC;
END
GO
BEGIN
DECLARE @tablename VARCHAR(128);
DECLARE @tableid INT;
SET @tablename = 'Mytablename';
SELECT so.id INTO @tableid FROM sysobjects so WHERE so.name = @tablename;
SELECT * FROM FLA_distinctCols(@tableid);
END
还有其他解决方案吗?