如何获取列值不为空的行

How to get rows whose columns values are not null(如何获取列值不为空的行)
本文介绍了如何获取列值不为空的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想获取表中没有列值为空的行.没有对列值进行硬编码.我有数百个列名.

I want to get rows of a table such that no column value is null. No hardcoding of column values. I have hundreds of column names so.

输出应该只有第 2 行,因为所有该行都包含所有列的值.我不想为 is not null 指定所有列名.它应该以编程方式接受它.即使我添加了一个新列,它也应该可以在不更改查询的情况下工作.这是我的愿景.

Output should be only row 2 since all that row has the values for all the columns. I do not want to specify all the column names for is not null. It should take it programmatically. Even if i add a new column it should work without changing the query. That is my vision.

推荐答案

我找到了一些东西,但这意味着使用 CURSOR

I found something, but that means using CURSOR

DECLARE @ColumnName VARCHAR(200)
DECLARE @ColumnCount INT
DECLARE @sql VARCHAR(400)

CREATE TABLE #tempTable (Id INT)

DECLARE GetNonNullRows CURSOR 
FOR 
    SELECT c.NAME, (SELECT COUNT(*) FROM sys.columns col WHERE col.object_id = c.OBJECT_ID)  FROM sys.tables AS t
    JOIN sys.columns AS c ON t.object_id = c.object_id
    WHERE t.name = 'SomeTable' AND t.type = 'U'

OPEN GetNonNullRows
FETCH NEXT FROM GetNonNullRows INTO @ColumnName, @ColumnCount
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = 'SELECT st.UniqueId FROM SomeTable AS st WHERE ' + CONVERT(varchar, @ColumnName) + ' IS NOT NULL'    
    INSERT INTO #tempTable
    EXEC (@sql)

FETCH NEXT FROM GetNonNullRows INTO @ColumnName, @ColumnCount
END 

CLOSE GetNonNullRows
DEALLOCATE GetNonNullRows

SELECT * FROM SomeTable AS st1
WHERE st1.UniqueId IN (SELECT Id FROM #tempTable AS tt
GROUP BY Id
HAVING COUNT(Id) = @ColumnCount)


DROP TABLE #tempTable

让我稍微解释一下.

首先我创建游标,它遍历一个表的所有列.对于每一列,我创建了 sql 脚本来在表中搜索所选列的非空值.对于那些满足条件的行,我取其唯一 ID 并放入临时表中,我将这项工作用于所有列.

First i create cursor which iterate through all the columns of one table. For each column, I've create sql script to search in table for not null values for selected column. For those rows that satisfies criteria, I take its unique ID and put in temp table, and this job I am using for all columns.

最后,只有像列数一样计数的 ID 才是您的结果集,因为只有具有相同出现次数(如表中的列数)的行才可能是所有列中都包含非空值的行.

At the end only ID's which count is like columns count are your result set, because only rows that have identical number of appearances like number of columns in table may be rows with all non null values in all columns.

这篇关于如何获取列值不为空的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)